刷题《剑指Offer》day06

题目来源:力扣《剑指Offer》第二版
完成时间:2022/07/27

15. 二进制中1的个数

image-20220729113656557

我的题解

主要思路就是不断地右移,和1做与运算。

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int count = 0;
        while(n) {
            if(n & 1){
                count++;
            }
            n = n >> 1;
        }
        return count;
    }
};

16. 数值的整数次方

image-20220729113918150

我的题解

这道题有个巨坑的地方,就是给定的n可能会超范围,要用一个long接收一下,我一开始没找到思路,用的书上原码过的。大致思想和斐波那契数列有点像,比如13次方可以拆解成6+6+1,6又拆解为3+3,以此类推。

class Solution {
public:
    double myPow(double x, int n) {
        long m = n;//巨坑
        if(n >= 0) return count(x,m);
        else return count(1 / x, -m);
    }

    double count(double x, long n) {
        if(n == 0) return 1;
        if(n == 1) return x;

        double result = myPow(x,n >> 1);
        result *= result;
        if(n % 2 == 1){
            result *= x;
        }
        return result;
    }
};

其他题解

这个就比较取巧,和上一题类似,用二进制的思路,不断右移。比如13就是1101,即1+0+4+8,碰到1就可以进行运算。

double myPow(double x, int n) {
	double res = 1;
	long y = n;
	if (n < 0) {
		y = -y;
		x = 1 / x;
	}
	while (y > 0) {
		if (y % 2 == 1) {//判断最后一位是否为1
			res = res * x;
		}
		x = x * x;
		y = y >> 1;//右移
	}
	return res;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值