Problem Statement
The binary weight of a positive integer is the number of 1's in its binary representation. For example, the decimal number 1 has a binary weight of 1, and the decimal number 1717 (which is 11010110101 in binary) has a binary weight of 7.
Given a positive integer N, return the smallest integer greater than N that has the same binary weight as N.
Definition
- Class:
- NextNumber
- Method:
- getNextNumber
- Parameters:
- int
- Returns:
- int
- Method signature:
- int getNextNumber(int N)
- (be sure your method is public)
Notes
- The result is guaranteed to fit in a signed 32-bit integer.
Constraints
- N will be between 1 and 1,000,000,000, inclusive.
Examples
1717
Returns: 1718
Example from the problem statement.
1
Returns: 2
2
Returns: 4
4
Returns: 8
4 is 100 in its binary representation and weighs 1. The next number is 1000(in binary) which represents 8.
1024
Returns: 2048
1048576
Returns: 2097152
268435456
Returns: 536870912
536870910
Returns: 671088639
536870911
Returns: 805306367
536870912
Returns: 1073741824
805306368
Returns: 1073741825
973078527
Returns: 989855743
805306367
Returns: 939524095
939524096
Returns: 1073741827
268435454
Returns: 335544319
268435455
Returns: 402653183
500000000
Returns: 500000256
800000000
Returns: 800002048
900000000
Returns: 900000256
999990000
Returns: 999990023
999999999
Returns: 1000000255
1000000000
Returns: 1000000512
7
Returns: 11
The decimal 7 is binary 111, so it has binary weight of 3. The next number with the same binary weight is 11, which is 1011 in binary.
12
Returns: 17
12 in decimal is 1100 in binary. The next number with the same binary weight is 10001 in binary, which is 17.
555555
Returns: 555557
469762048
Returns: 536870915
54
Returns: 57
44
Returns: 49
33554432
Returns: 67108864
22
Returns: 25
249209942
Returns: 249209945
402653184
Returns: 536870913
7663672
Returns: 7663683
671088640
Returns: 805306368
5354378
Returns: 5354380
67108864
Returns: 134217728
949209942
Returns: 949209945
268419072
Returns: 268443647
555555678
Returns: 555555687
60
Returns: 71
805240880
Returns: 805240897
94
Returns: 103
46
Returns: 51
88
Returns: 97
536854528
Returns: 536887295
80
Returns: 96
15
Returns: 23
134217727
Returns: 201326591
1718
Returns: 1721
24
Returns: 33
805306364
Returns: 838860799
348
Returns: 355
92
Returns: 99
28
Returns: 35
6482136
Returns: 6482145
924
Returns: 931
76
Returns: 81
36
Returns: 40
1984
Returns: 2063
1564
Returns: 1571
316
Returns: 327
184
Returns: 195
992
Returns: 1039