Table of contents
Open Table of contents
Description
Receives a positive integer n.
Outputs a positive integer representing the smallest integer power of 2 greater than n.
The data guarantees that the result is within the
unsigned intdata range.
Example
Input Sample 1:
4
Output sample 1:
8
2^0 = 12^1 = 22^2 = 42^3 = 8So the smallest integer power of2larger than4is8.
Input Sample 2:
13
Output Example 2:
16
The integer powers of
2are1, 2, 4, 8, 16, 32...The smallest integer power of2greater than13is16.
Hide Hint
- Unsigned integer variables are declared with the
unsignedmodifier. - Shifting
1bit left is equivalent to multiplying2.
Solution
Idea
We can start from 2 and multiply the result by 2 until it is greater than n.
To check the integral data limits, it is better to check the official language reference. For C++, you can check the size of the various types of integers such as int, char, and unsigned long long at cppreference. The question mentioned the result can fit in unsigned int.
Complexity: Time , Space .
C++
#include <iostream>
using namespace std;
int main() {
int n; cin >> n;
unsigned int res = 2;
while (res<=n) res <<= 1;
cout << res;
return 0;
}