How to find the largest power of 2 less than the given number
Posted
by
nazar_art
on Stack Overflow
See other posts from Stack Overflow
or by nazar_art
Published on 2013-06-29T10:05:23Z
Indexed on
2013/06/29
10:21 UTC
Read the original article
Hit count: 150
I need to find the largest power of 2 less than the given number.
And I stuck and can't find any solution.
Code:
public class MathPow
{
public int largestPowerOf2 (int n)
{
int res = 2;
while (res < n) {
res =(int)Math.pow(res, 2);
}
return res;
}
}
This doesn't work correctly.
Testing output:
Arguments Actual Expected
-------------------------
9 16 8
100 256 64
1000 65536 512
64 256 32
How to solve this issue?
© Stack Overflow or respective owner