标签:
原题链接在这里:https://leetcode.com/problems/reverse-bits/
新学了一种API, Integer.reverse()可以直接返回binary的reverse. 参考链接:http://www.tutorialspoint.com/java/lang/integer_reverse.htm
Method 2 取出最后一位digit,res左移以为加上digit. 但需要注意的是loop中需要res先左移以为在加digit, 若是在loop中先写加digit再左移会把首位溢出掉。
e.g. 如果是 32位的int, 其实能够左移的只有31位。
AC Java:
1 public class Solution { 2 // you need treat n as an unsigned value 3 public int reverseBits(int n) { 4 /* 5 //Method 1 6 return Integer.reverse(n); 7 */ 8 9 //Method 2 10 int res = 0; 11 for(int i = 0; i<32; i++){ 12 int digit = n&1; 13 n = n>>1; 14 15 res = res<<1; 16 res+=digit; 17 } 18 return res; 19 } 20 }
标签:
原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/4833912.html