Halving to Zero
1.0s 256MYou are given a positive integer \(n\).
In one operation, replace the current value of \(n\) by the integer result of dividing it by \(2\), discarding the fractional part. How many operations are needed before \(n\) becomes \(0\)?
For example, when \(n = 13\), the values are:
13 -> 6 -> 3 -> 1 -> 0
This takes \(4\) operations, so the answer is \(4\).
Syntax Restrictions
This problem uses the syntax restrictions of Unit 4 (Loops) of the syntax textbook. You may use if, else, loops, comparisons, logical operators, integer variables, cin, cout, and cout << endl; however, you may not use arrays or containers, and you may not use any function other than main (including built-in functions and user-defined functions). The name endl is allowed only as an output newline manipulator, not as a function call.
Your source code is checked automatically during judging. A submission that breaks the restrictions is judged SR (Syntax Restriction), and the judge feedback lists where the violation is.
Click to expand: allowed and forbidden syntax
Allowed:
#include <iostream>or other ordinary includes (no extra header is needed)using namespace std;- the
int main()function andreturn 0; - integer, Boolean, and character variables, such as
int,long long,bool, andchar - reading with
cin >>and printing withcout <<, includingcout << endl if,else,for, andwhile- arithmetic, comparison, and logical operators, such as
+,-,*,/,%,<,<=,==, and&& - assignment and increment/decrement, such as
=,+=,++, and-- - comments (
//and/* */)
Forbidden (common examples):
- arrays and indexing syntax
[] - containers or similar tools such as
vector,array,string,deque,map, andset - dynamic allocation syntax such as
newanddelete - any function call or function declaration other than
main, includingmax,min,abs,sqrt,pow,sort,swap,getline,printf, andscanf - non-include preprocessor directives such as
#define
Input
The input contains one line with one positive integer \(n\).
Constraints
- \(1 \le n \le 2 \times 10^9\)
- The memory limit is \(256\) MB.
Output
Output one integer: the number of integer divisions by \(2\) needed before \(n\) becomes \(0\).
Sample Input 1
13
Sample Output 1
4
Sample Input 2
1
Sample Output 2
1
Sample Input 3
2000000000
Sample Output 3
31
Source
Adapted from the example "折半歸零要幾次" in AACPOJ Syntax Book Volume 1, 4.2 while loops.
Log in to write and submit code. Creating an account is free.