Heman, Anil, and Soubhik are playing a fun card game. They have an ordered deck of N cards numbered from 1 to N with card 1 at the top and card N at the bottom.
Heman and Anil both perform an operation on the deck as long as there is exactly 1 card on the deck. Heman will throw away the card on the top and then Anil moves the card that is now on the top of the deck to the bottom. Soubhik has to find the number on the final card left in the deck, your job is to help him to do so.
Example:
Input: n = 5
Output: 2
Approach
C++
#include <bits/stdc++.h>using namespace std;int finalCardNumber(int n){int p = 1;while (n != 1){if (pow(2, p) > n)break;p += 1;}p = p - 1;if (pow(2, p) == n)return n;elsereturn ((n - pow(2, p)) * 2);}int main(){int n = 5;cout << finalCardNumber(n) << "\n";return 0;}
No comments:
Post a Comment