【无标题】

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值