Advertisement
Guest User

Untitled

a guest
Apr 25th, 2015
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.48 KB | None | 0 0
  1. /*
  2. Method 1:
  3. Algorithm: SHIFT and count the number of 1
  4. Integer的范围是(-2^31) ~ (2^31-1), 32位是符号位
  5. */
  6. public boolean isPowerOfTwo(int a) {
  7. int count = 0;
  8. for(int i=0;i<31;i++) {
  9. if(((a>>i) & 1) == 1) {
  10. count++;
  11. }
  12. }
  13. return count <=1;
  14. }
  15.  
  16. /*
  17. Method 2:
  18. 3 = 11
  19. 4 = 100
  20. 7 = 111
  21. 8 = 1000
  22. 所有的power of 2 number都有一个特性 number & (number -1) = 0
  23. */
  24. public boolean isPowerOfTwo(int a) {
  25. if(a < 1) {
  26. return false;
  27. }
  28. return (a & (a-1)) == 0;
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement