当前位置:网站首页>刷题《剑指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;
}
边栏推荐
- 【Unity】编辑器扩展-04-拓展Scene视图
- Linux redis6.2.6 configuration file
- 7/28-7/29 Expectation + thinking + suffix array + ST table
- 35-Jenkins-Shared library application
- 0730~Mysql optimization
- Which strings will be parsed as null by FastJson?
- 期刊会议排名、信息检索网站推荐以及IEEE Latex模板下载
- MySQL 8.0.29 解压版安装教程(亲测有效)
- UML图及在drawio中的绘制
- 射频电路学习之滤波电路
猜你喜欢

实用生物信息学2:多组学数据整合和挖掘

Small application project development, jingdong mall 】 【 uni - app custom search component (below) - search history

How to upgrade nodejs version

【云原生与5G】微服务加持5G核心网

sqli-labs(less-11)

Install the deployment kubernetes KubeSphere management

Vscode: Project-tree plugin

SSM整合案例分析(详解)

《如何戒掉坏习惯》读书笔记

Flutter Paystack 所有选项实现
随机推荐
skynet中一条消息从取出到处理完整流程(源码刨析)
vscode输出中文乱码问题
Docker-compose安装mysql
一、MySQL主从复制原理
数组every和some方法的区别?
Read Elephant Swap in one article, why does it bring such a high premium to ePLATO?
sqli-labs(less-11)
报销流程|By天放师兄
UML图及在drawio中的绘制
科目三:前方路口直行
普通函数的参数校验
【问题记录】TypeError: eval() arg 1 must be a string, bytes or code object
蚂蚁核心科技产品亮相数字中国建设峰会 持续助力企业数字化转型
MySQL 数据库基础知识(系统化一篇入门)
[MySQL exercises] Chapter 2 Basic operations of databases and data tables
SSM framework explanation (the most detailed article in history)
云服务器部署 Web 项目
MySQL安装常见报错处理大全
C# 正则表达式汇总
[Cloud native] Introduction and use of Feign of microservices