当前位置:网站首页>刷题《剑指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;
}
边栏推荐
- Doraemon teach you forwarded and redirect page
- MySQL 8.0.29 解压版安装教程(亲测有效)
- 35-Jenkins-Shared library application
- "The C language games" mine clearance
- SSM框架简单介绍
- 如何使用mysql binlog 恢复数据
- MySQL 5.7升级到8.0详细过程
- TypeError The view function did not return a valid response. The function either returned None 的解决
- 循环结构--for循环
- 【小程序项目开发-- 京东商城】uni-app之商品列表页面 (上)
猜你喜欢

【Unity】编辑器扩展-02-拓展Hierarchy视图

【问题记录】TypeError: eval() arg 1 must be a string, bytes or code object

【MySQL中auto_increment有什么作用?】

The torch distributed training

【黄啊码】MySQL入门—3、我用select ,老板直接赶我坐火车回家去,买的还是站票

SQL statement knowledge

SSM framework explanation (the most detailed article in history)

Open Source | Commodity Recognition Recommender System

【小程序专栏】总结uniapp开发小程序的开发规范

Practical Bioinformatics 2: Multi-omics data integration and mining
随机推荐
剑指offer-解决面试题的思路
Practical Bioinformatics 2: Multi-omics data integration and mining
SQL join table (inner join, left join, right join, cross join, full outer join)
哪些字符串会被FastJson解析为null呢
如何在一台机器上(windows)安装两个MYSQL数据库
基于golang的swagger超贴心、超详细使用指南【有很多坑】
信息收集-DNS
深度学习随机数设置,保证实验的可重复性
[Mini Program Project Development--Jingdong Mall] Custom Search Component of uni-app (Part 1)--Component UI
Cloud server deployment web project
MySQL安装教程
如何使用mysql binlog 恢复数据
MySQL 8.0.29 解压版安装教程(亲测有效)
Open Source | Commodity Recognition Recommender System
【MySQL功法】第2话 · 数据库与数据表的基本操作
【小程序项目开发-- 京东商城】uni-app之自定义搜索组件(中)-- 搜索建议
SQLAlchemy使用教程
科目三:右转弯
How to Install MySQL on Linux
0730~Mysql optimization