位运算
# 7. 整数反转 (opens new window)
class Solution {
public int reverse(int x) {
int ret = 0;
while(x!=0){
if(ret>Integer.MAX_VALUE/10 || ret<Integer.MIN_VALUE/10)
return 0;
ret = ret*10 + x%10;
x /= 10;
}
return ret;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 9. 回文数 (opens new window)
class Solution {
public boolean isPalindrome(int x) {
// 负数不是回文,最后一位数字为0则第一位数字也得为0
if(x<0 || (x%10==0&&x!=0))
return false;
int rev = 0;
while(x>rev){
rev = rev*10 + x%10;
x /= 10;
}
// 数字长度分为 奇数或偶数
return x==rev || x==rev/10;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 136. 只出现一次的数字 (opens new window)
方法一:位运算
class Solution {
public int singleNumber(int[] nums) {
int ret = 0;
for(int num:nums){
ret ^= num;
}
return ret;
}
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
方法二:API
public class Solution {
public int hammingWeight(int n) {
return Integer.bitCount(n);
}
}
1
2
3
4
5
2
3
4
5
# 191. 位1的个数 (opens new window)
方法一:逐位判断
class Solution {
public int hammingWeight(int n) {
int res = 0;
while(n!=0){
res += n&1;
n >>>= 1;
}
return res;
}
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
方法二:n&(n-1)
最右边的1变为0;
class Solution {
public int hammingWeight(int n) {
int res = 0;
while(n!=0){
res++;
n &= (n-1);
}
return res;
}
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10