【无标题】

【无标题】,第1张

【无标题】

 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 的幂

  • 重点在于对位运算符的理解
  • 解法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;
    }
};

 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;
     }
};

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5660385.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存