递归
class Solution {
public:
int sumNums(int n) {
int res = n;
n>0 && (res+= (sumNums(n-1)));
return res;
}
};
2. 231. 2 的幂
- 重点在于对位运算符的理解
- 解法1:&运算,同1则1。
return (n > 0) && (n & -n) == n;
- 解释:2的幂次方在二进制下,只有1位是1,其余全是0。例如:8---00001000。负数的在计算机中二进制表示为补码。然后两者进行与操作,得到的肯定是原码中最后一个二进制的1。例如8&(-8)->00001000 & 11111000 得 00001000,即8。
class Solution {
public:
bool isPowerOfTwo(int n) {
return n > 0 && (n & -n) == n;
}
};
1162261467是int范围内最大的3的幂次方
class Solution {
public:
bool isPowerOfThree(int n) {
return n > 0 && 1162261467 % n == 0;
}
};
4.342. 4的幂
class Solution {
public:
bool isPowerOfFour(int n) {
if(n <= 0) return false;
int r = sqrt(n);
if(r*r != n) return false;
return (n & -n) == n;
}
};
遍历 是余数k-1
class Solution {
public:
int kthFactor(int n, int k) {
for(int i = 1;i<=n;i++){
if(n%i == 0) k--;
if(k == 0) return i;
}
return -1;
}
};
class Solution {
public:
bool isPerfectSquare(int num) {
int l = 1,r = num;
while(l < r){
int mid = l + 1ll + r >> 1;
if(mid <= num / mid) l = mid;
else r = mid - 1;
}
return r * r == num;
}
};
二分
class Solution {
public:
bool isPerfectSquare(int num) {
int l = 1,r = num;
while(l < r){
int mid = l + 1ll + r >> 1;
if(mid <= num / mid) l = mid;
else r = mid - 1;
}
return r * r == num;
}
};