首页 > 其他 > 详细

LeetCode Reverse Bits

时间:2015-09-24 00:39:30      阅读:157      评论:0      收藏:0      [点我收藏+]

原题链接在这里: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 }

 

LeetCode Reverse Bits

原文:http://www.cnblogs.com/Dylan-Java-NYC/p/4833912.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!