[easy]Power of Two

难度: 简单 标题:2的冥

Given an integer, write a function to determine if it is a power of two.

判断一个是否是2的幂。

思路

一个数转换成二进制后,假如此数为2的冥,则它的形式一定是100…000。

所以只要不断右移,计算1出现的次数。n & 1 ,假如 n 末尾为1,则结果为1.末尾为 0,结果为 0;

代码

1
2
3
4
5
6
7
8
9
10
public class Solution {
public boolean isPowerOfTwo(int n) {
int ctz = 0;
while(n > 0){
ctz += (n & 1);
n = n >> 1;
}
return ctz == 1;
}
}

链接

https://leetcode.com/problems/power-of-two/

[easy]Sum of Two Integers

难度: 中等 标题:两数求和

leetcode Sum of Two Integers

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

Example:
Given a = 1 and b = 2, return 3.

求两数只和,不能用加法和减法。

思路

a ^ b 表示求和且不进位。a & b 表示按位求与,(a & b) * 2 即为进位。

所以 a + b = ((a & b)<<1) + a ^ b;直到进位为0时。结果就是我们所需要的结果。

代码

1
2
3
4
5
6
7
8
9
10
public class Solution {
public int getSum(int a, int b) {
while(b!=0){
int c = a & b;
a = a ^ b;
b = c << 1;
}
return a;
}
}

链接

https://leetcode.com/problems/sum-of-two-integers/

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×