Advertisement
Guest User

Untitled

a guest
May 28th, 2015
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.83 KB | None | 0 0
  1. //by dnalwqer 04/19/2015
  2. //idea: use an bit number to track whether it is an odd bit or even bit.
  3.  
  4.  
  5. public class Solution {
  6. public int reverseBits(int A) {
  7. int bit = 0;
  8. int res = 0;
  9.  
  10. while (A != 0) {
  11. int num = A & 1;
  12. A = A >>> 1;
  13. if (num == 1) {
  14. if (bit % 2 == 0) {
  15. res |= 1 << (bit + 1);
  16. }
  17. else {
  18. res |= 1 << (bit - 1);
  19. }
  20. }
  21. bit++;
  22. }
  23. return res;
  24. }
  25.  
  26. // I have learnt a new method
  27. // use 0x55555555 to reset all the odd bits to 0 and shift left to get all the right odd numbers, vice verse.
  28.  
  29. public int reverseBits2(int A) {
  30. return ((0x55555555 & A) << 1) | ((0xAAAAAAAA) & A) >> 1);
  31. }
  32.  
  33. public static void main(String []args) {
  34. Solution s = new Solution();
  35. int A = Integer.parseInt("011110", 2);
  36. int res = s.reverseBits(A);
  37. System.out.println(Integer.toBinaryString(res));
  38. }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement