Reputation: 11
I have tried writing a java program to find a number is power of two the one which i mentioned below.
I am passing number as 2147483647 and the output of my program is returning true instead of false. Can anyone explain what concept I am missing here and how to correct it.
Program
class Solution {
public boolean isPowerOfTwo(int n) {
int num = 0;
int p = 0;
while(num <= n){
num = (int) Math.pow(2,p);
p++;
if(num == n){
return true;
}
}
return false;
}
}
public static void main(String[] args) {
enter code here
boolean val = isPowerOfTwo(2147483647);
}
Upvotes: 1
Views: 96
Reputation: 198004
If a double
is greater than Integer.MAX_VALUE
, then casting it to an int
will give you Integer.MAX_VALUE
.
The number you give is Integer.MAX_VALUE
, so of course it's going to be equal to sufficiently large values of (int) Math.pow(2, p)
.
You will need a different approach, such as actually doubling an int value instead of just calling Math.pow
, or some more sophisticated approach. (The usual ultra-optimized solution is x >= 0 && (x & (x - 1)) == 0
, but you probably won't understand that or why it works yet.)
Upvotes: 4