190. Reverse Bits 颠倒二进制位 #Bit Manipulation

190. Reverse Bits

https://leetcode.com/problems/reverse-bits/

Description

Reverse bits of a given 32 bits unsigned integer.

Example 1:

Input: 00000010100101000001111010011100
Output: 00111001011110000010100101000000
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.
Example 2:

Input: 11111111111111111111111111111101
Output: 10111111111111111111111111111111
Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10101111110010110010011101101001.

Note:

Note that in some languages such as Java, there is no unsigned integer type. In this case, both input and output will be given as signed integer type and should not affect your implementation, as the internal binary representation of the integer is the same whether it is signed or unsigned.
In Java, the compiler represents the signed integers using 2’s complement notation. Therefore, in Example 2 above the input represents the signed integer -3 and the output represents the signed integer -1073741825.

Solutions

  1. 用了反转十进制数的思路,但是会通不过前缀是0的int(较小的int)
    比如00000010100101000001111010011100,while就只会运行到10100101000001111010011100就结束了,之前的000000就跳出while了。
  2. Integer.reverse(n)就可以了!

Submissions

我的~

public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        int res=0;
        while(n>0)
        {
            int digi=n%2;
            n/=2;
            res=res*2+digi;
        }
        return res;
    }
}

位运算的方法:

public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        int res = 0;
		for(int i=0;i<32;i++)//操作32次移位操作
		{
			res<<=1;//结果左移一位,空出位置与n最后一位相加
			res+=n&1; //加上n的最后一位
			n>>=1; //n右移一位,供下一轮与结果相加
		}
        return res;
    }
}

Summary

  1. 位运算
    Java 位运算(移位、位与、或、异或、非)
  2. java中,整数默认就是int类型,也就是32位
  3. Integer.reverse(n)
    java源代码Integer类中提供了reverse(int i)方法,这个方法的作用是用来将int类型变量的二进制表示进行按位反转
    https://www.geeksforgeeks.org/integer-reverse-method-in-java/
  4. If this function is called many times, how would you optimize it?
    题解 https://blog.csdn.net/u013190513/article/details/70593257
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值