1.剑指 Offer 64. 求1+2+…+n
class Solution { public: int sumNums(int n) { int res = n; n>0 && (res+= (sumNums(n-1))); return res; } };
2. 231. 2 的幂
class Solution { public: bool isPowerOfTwo(int n) { return n > 0 && (n & -n) == n; } };
3.326. 3 的幂
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; } };
5.1492. n 的第 k 个因子
遍历 是余数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; } };
6.367. 有效的完全平方数
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; } };
367. 有效的完全平方数
二分
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; } };
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)