190. Reverse Bits

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
    }
}

 

posted @ 2020-03-08 00:25  johnny_zhao  阅读(107)  评论(0编辑  收藏  举报