【190-Reverse Bits(反转二制)】

 

2015年08月24日 07:15:15 derrantcm 阅读数:4198 标签: 数字二进制算法面试java 更多

个人分类: LeetCode

所属专栏: LeetCode

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/DERRANTCM/article/details/47945389

【190-Reverse Bits(反转二制)】


【LeetCode-面试算法经典-Java实现】【所有题目目录索引】


代码下载【https://github.com/Wang-Jun-Chao】

原题

  Reverse bits of a given 32 bits unsigned integer. 
  For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000). 
  Follow up: 
  If this function is called many times, how would you optimize it? 

题目大意

  反转一个32位无符号的整数。 

解题思路

  设这个数为k,用一个初值为0的数r保存反转后的结果,用1对k进行求与,其结果与r进行相加,再对k向右进行一位移位,对r向左进行一位移位。值到k的最后一位处理完。 

代码实现

算法实现类

<span style="color:#000000"><code><span style="color:#000088 !important">public</span> <span style="color:#000088 !important">class</span> Solution {

    <span style="color:#000088 !important">public</span> <span style="color:#000088 !important">int</span> <span style="color:#009900 !important">reverseBits</span>(<span style="color:#000088 !important">int</span> n) {

        <span style="color:#000088 !important">int</span> result = <span style="color:#006666 !important">0</span>;
        <span style="color:#000088 !important">for</span> (<span style="color:#000088 !important">int</span> i = <span style="color:#006666 !important">0</span>; i < <span style="color:#006666 !important">32</span>; i++) {
            result += n & <span style="color:#006666 !important">1</span>;
            n >>>= <span style="color:#006666 !important">1</span>;
            <span style="color:#000088 !important">if</span> (i < <span style="color:#006666 !important">31</span>) {
                result <<= <span style="color:#006666 !important">1</span>;
            }
        }
        <span style="color:#000088 !important">return</span> result;
    }
}</code></span>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

评测结果

  点击图片,鼠标不释放,拖动一段位置,释放后在新的窗口中查看完整图片。

【190-Reverse Bits(反转二制)】