码迷,mamicode.com
首页 > 编程语言 > 详细

190. Reverse Bits Java Solutin

时间:2016-04-15 21:35:57      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:

Reverse bits of a given 32 bits unsigned integer.

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).

Follow up:
If this function is called many times, how would you optimize it?

Related problem: Reverse Integer

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

 

Subscribe to see which companies asked this question

 1 public class Solution {
 2     // you need treat n as an unsigned value
 3     public int reverseBits(int n) {
 4         //return Integer.reverse(n);
 5         int result = 0;
 6         for(int i = 0 ;i < 32; i++){
 7             int tmp = (n&1);
 8             n = n >> 1;
 9             result = result << 1;
10             result += tmp;
11         }
12         return result;
13     }
14 }

使用 Integer.reverse() API 直接AC。

每一次取出n的末尾二进制数字,result左移移位,将移出的数字加到result末尾,循环32次后,既得结果。

190. Reverse Bits Java Solutin

标签:

原文地址:http://www.cnblogs.com/guoguolan/p/5396699.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!