fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. int n;
  13. int result;
  14. for (n=0;n<=16;n++) {
  15. result = nextPower2(n);
  16. System.out.println("Next power of " + n + " is " + result);
  17. }
  18. }
  19.  
  20. static int nextPower(int n) {
  21. int result;
  22. result = nextPower1(n);
  23. if (n<=1 || result ==n)
  24. return result;
  25. else
  26. return result * 2;
  27. }
  28.  
  29. static int nextPower2( int n ) {
  30. if (n == 1) return 1;
  31. if (n == 2) return 2;
  32. if (n == 3) return 4;
  33. return nextPower((n >> 1) | (n & 1)) << 1;
  34. }
  35.  
  36. static int nextPower1(int n) {
  37. if(n == 0) {
  38. return 1;
  39. } else if(n == 1) {
  40. return 1;
  41. } else {
  42. int lastBit = n & 1;
  43. int secondLastBit = (n >> 1) & 1;
  44. int restOfTheBits = (n >> 2);
  45.  
  46. int result = nextPower1(restOfTheBits << 1 | secondLastBit ^ lastBit);
  47. return result << 1;
  48. }
  49. }
  50. }
Success #stdin #stdout 0.1s 320256KB
stdin
Standard input is empty
stdout
Next power of 0 is 2
Next power of 1 is 1
Next power of 2 is 2
Next power of 3 is 4
Next power of 4 is 4
Next power of 5 is 8
Next power of 6 is 8
Next power of 7 is 8
Next power of 8 is 8
Next power of 9 is 16
Next power of 10 is 16
Next power of 11 is 16
Next power of 12 is 16
Next power of 13 is 16
Next power of 14 is 16
Next power of 15 is 16
Next power of 16 is 16