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
- 用了反转十进制数的思路,但是会通不过前缀是0的int(较小的int)
比如00000010100101000001111010011100,while就只会运行到10100101000001111010011100就结束了,之前的000000就跳出while了。 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
- 位运算
Java 位运算(移位、位与、或、异或、非) - java中,整数默认就是int类型,也就是32位
Integer.reverse(n)
java源代码Integer类中提供了reverse(int i)方法,这个方法的作用是用来将int类型变量的二进制表示进行按位反转
https://www.geeksforgeeks.org/integer-reverse-method-in-java/- If this function is called many times, how would you optimize it?
题解 https://blog.csdn.net/u013190513/article/details/70593257