当前位置:网站首页>刷题《剑指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;
}
边栏推荐
猜你喜欢

SSM框架简单介绍
![[Cloud native] Introduction and use of Feign of microservices](/img/39/05cf7673155954c90e75a8a2eecd96.jpg)
[Cloud native] Introduction and use of Feign of microservices
![[Mini Program Project Development--Jingdong Mall] Custom Search Component of uni-app (Part 1)--Component UI](/img/73/a22ab1dbb46e743ffd5f78b40e66a2.png)
[Mini Program Project Development--Jingdong Mall] Custom Search Component of uni-app (Part 1)--Component UI

SQL 入门之第一讲——MySQL 8.0.29安装教程(windows 64位)

mysql安装教程【安装版】

WLAN部署(AC+AP)配置及常见问题记录

【MySQL功法】第3话 · MySQL中常见的数据类型
![[MySQL exercises] Chapter 3 Common data types in MySQL](/img/11/66b4908ed8f253d599942f35bde96a.png)
[MySQL exercises] Chapter 3 Common data types in MySQL

Docker-compose安装mysql

Locust 1.0版本引入的变化
随机推荐
使用MySQL如何查询一年中每月的记录数
regex bypass
C语言三子棋(井字棋)小游戏
免安装版的Mysql安装与配置——详细教程
信息收集-DNS
Vue项目通过node连接MySQL数据库并实现增删改查操作
Reimbursement Process | By Tianfang
Locust 1.0版本引入的变化
Ubuntu22.04安装mysql
【C#】说说 C# 9 新特性的实际运用
sqlmap使用教程大全命令大全(图文)
tqdm库的使用
The first part of the R language
【面试题】从输入URL到游览器渲染完成,经历了什么
"C language" frog jumping steps recursion problem
2022杭电杯超级联赛3
35-Jenkins-Shared library application
动态顺序表的增删查改(C语言实现)
Install the deployment kubernetes KubeSphere management
MUI获取相机权限