首页 > 其他 > 详细

190. Reverse Bits

时间:2020-03-08 09:11:20      阅读:70      评论:0      收藏:0      [点我收藏+]
package LeetCode_190

/**
 * 190. Reverse Bits
 * https://leetcode.com/problems/reverse-bits/description/
 * Reverse bits of a given 32 bits unsigned integer.
 *
 * 如10进制,反转一个数:n
 * result = result*10+n%10
 * n /= 10
 *
 * do in Base-2 so for so on:但n是负数时,%2并不能得到正确的数,
 * 如: -3:
 * 11111111111111111111111111111101
 * result = result*2+n%2
 * n /= 2
 *
 * or use bit operators:
 * result  = (result << 1) | (n & 1)
 * n >>=1
 *
 * test case:
 * 43261596
 * */
class Solution {
    fun reverseBits(n_: Int): Int {
        var n = n_
        var result = 0
        for (i in 0 until 32) {
            result = (result shl 1) + (n and 1)
            n = n shr 1

            /*result = result * 2 + n % 2
            println("result:$result")
            n /= 2*/
        }
        //n=-3时:11111111111111111111111111111101
        //kotlin答案为负数:-1073741825
        //java的才正确为:3221225471,二进制为:10111111111111111111111111111111
        return result
    }
}

 

190. Reverse Bits

原文:https://www.cnblogs.com/johnnyzhao/p/12439458.html

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