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
.
题目是二进制的翻转:
//第一次写代码写成了10进制翻转,后来发现是不可行的,因为0*10+0=0,而不是00。
//第二次写成了int转换成String翻转,之后再把String转换成int,结果会出错。
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
String s=Integer.toString(n);//一定要注意String的首字母是大写的
int len=s.length();
String temp="";
for(int i=len-1;i>=0;i--){
temp=temp+s.charAt(i);
}
//int res=Integer.valueOf(temp);//String转换成int
int res=Integer.parseInt(temp);
return res;
}
}
这里注意一下int与String的相互转换:
1如何将字串 String 转换成整数 int?
A. 有两个方法:
1). int i = Integer.parseInt(str);
2). int i = Integer.valueOf(str).intValue();
注: 字串转成 Double, Float, Long 的方法大同小异.
2 如何将整数 int 转换成字串 String ?
A. 有叁种方法:
1.) String s = String.valueOf(i);
2.) String s = Integer.toString(i);
3.) String s = "" + i;
注: Double, Float, Long 转成字串的方法大同小异.
参考了网上的思路:
//解题思路: 设这个数为n,用一个初值为0的数res保存反转后的结果,用1对n进行求与,其结果与res进行相加,再对n向右进行一位移位,对r向左进行一位移位。值到n的最后一位处理完。
public class Solution {
public int reverseBits(int n) {
int res = 0;
for (int i = 0; i < 32; i++) {
res <<= 1;//首先将结果res左移变大
if ((n & 1) == 1 ) {//如果当前位置为1,则res++,当前为0的话则保持仅左移不变,注意相与的写法
res++;
}
n >>= 1;//n右移变小,移到下一位,注意移位的写法
}
return res;
}
}