Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MathPow
- {
- public int largestPowerOf2 (int n)
- {
- int res = 2;
- while (res < n) {
- res =(int)Math.pow(res, 2);
- }
- return res;
- }
- }
- Arguments Actual Expected
- -------------------------
- 9 16 8
- 100 256 64
- 1000 65536 512
- 64 256 32
- Integer.highestOneBit(n-1);
- v--;
- v |= v >> 1;
- v |= v >> 2;
- v |= v >> 4;
- v |= v >> 8;
- v |= v >> 16;
- v++;
- v >>= 1;
- public int largestPowerOf2(int n) {
- return (int)Math.pow(2, Math.floor(Math.log(n) / Math.log(2));
- }
- 0x80000000 >>> Integer.numberOfLeadingZeros(n - 1);
- public class MathPow{
- public int largestPowerOf2(int n){
- if((n & n-1) == 0){ //this checks if n is a power of 2
- n--; //Since n is a power of 2 we have to subtract 1
- }
- while((n & n-1) != 0){ //the while will keep on going until n is a power of 2, in which case n will only have 1 bit on which is the maximum power of 2 less than n. You could eliminate the != 0 but just for clarity I left it in
- n = n & n-1; //we will then perform the bitwise operation AND with n and n-1 to eliminate the least significant bit of n
- }
- return n;
- }
- }
- 10101000
- & 10100111
- ------------
- 10100000
- 10100000
- & 10011111
- -------------
- 10000000
- 1111
- & 1110
- --------
- 1110
- 1110
- & 1101
- ---------
- 1100
- 1100
- & 1011
- --------
- 1000
- public class MathPow
- {
- public int largestPowerOf2 (int n)
- {
- int res = 2;
- while (res < n) {
- res =res*2;
- }
- return res;
- }
- }
- int res = 2;
- while (res * 2 < n) {
- res *= 2;
- }
- public static int nextPowDown(int x, int z) {
- if (x == 1)
- return z;
- return nextPowDown(x >> 1, z << 1);
- }
- public static int nextPowTailRec(int x) {
- return x <= 2 ? x : nextPowDown(x >> 1) << 1;
- }
- System.out.println(nextPowDown(60, 1)); // prints 32
- System.out.println(nextPowDown(24412, 1)); // prints 16384
- System.out.println(nextPowDown(Integer.MAX_VALUE, 1)); // prints 1073741824
- public class MathPow
- {
- public int largestPowerOf2(int n)
- {
- int res = 1;
- while (res <= (n-1)/2)
- {
- res = res * 2;
- }
- return res;
- }
- }
- p=2;
- while(p<=n)
- {
- p=2*p;
- }
- p=p/2;
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- String num = br.readLine();
- BigInteger in = new BigInteger(num);
- String temp = in.toString(2);
- System.out.println(new BigInteger("2").shiftLeft(temp.length() - 2));
- BigInteger nvalue = TWO.pow(BigIntegerMath.log2(value, RoundingMode.FLOOR));
- n = (x>>>0).toString(2).length-1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement