当前位置:网站首页>刷题《剑指Offer》day06
刷题《剑指Offer》day06
2022-07-31 08:11:00 【吃豆人编程】
题目来源:力扣《剑指Offer》第二版
完成时间:2022/07/27
15. 二进制中1的个数
我的题解
主要思路就是不断地右移,和1做与运算。
class Solution {
public:
int hammingWeight(uint32_t n) {
int count = 0;
while(n) {
if(n & 1){
count++;
}
n = n >> 1;
}
return count;
}
};
16. 数值的整数次方
我的题解
这道题有个巨坑的地方,就是给定的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;
}
边栏推荐
- 【idea 报错】 无效的目标发行版:17 的解决参考
- TypeError The view function did not return a valid response. The function either returned None 的解决
- First acquaintance with NK-RTU980 development board
- 【pytorch记录】pytorch的分布式 torch.distributed.launch 命令在做什么呢
- SQL语句知识大全
- 如何使用mysql binlog 恢复数据
- [MySQL exercises] Chapter 4 · Explore operators in MySQL with kiko
- 动态顺序表的增删查改(C语言实现)
- 如何升级nodejs版本
- I advise those juniors and juniors who have just started working: If you want to enter a big factory, you must master these core skills!Complete Learning Route!
猜你喜欢
随机推荐
35-Jenkins-共享库应用
mysql insert new field method
求职产品经理【九】求职季,如何写好一份简历?
哆啦a梦教你页面的转发与重定向
力扣 593. 有效的正方形
mysql 数据去重的三种方式[实战]
SSM framework explanation (the most detailed article in history)
免安装版的Mysql安装与配置——详细教程
【小程序项目开发-- 京东商城】uni-app之自定义搜索组件(中)-- 搜索建议
NK - RTU980 burning bare-metal program
【MySQL功法】第2话 · 数据库与数据表的基本操作
Regarding "computing power", this article is worth reading
Linux redis6.2.6 configuration file
[Cloud native] Introduction and use of Feign of microservices
深度理解递归,手撕经典递归问题(汉诺塔,青蛙跳台阶),保姆级教学。
SQL 嵌套 N 层太长太难写怎么办?
【MySQL功法】第3话 · MySQL中常见的数据类型
【小程序专栏】总结uniapp开发小程序的开发规范
First acquaintance with NK-RTU980 development board
期刊投递时的 Late News Submission 是什么