当前位置:网站首页>刷题《剑指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;
}
边栏推荐
- 如何在一台机器上(windows)安装两个MYSQL数据库
- 【C#】说说 C# 9 新特性的实际运用
- A, MySQL principle of master-slave replication
- 哆啦a梦教你页面的转发与重定向
- 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!
- 使用PageHelper实现分页查询(详细)
- [MySQL exercises] Chapter 2 Basic operations of databases and data tables
- 重装系统后,hosts文件配置后不生效
- 【小程序专栏】总结uniapp开发小程序的开发规范
- sqlmap使用教程大全命令大全(图文)
猜你喜欢

全国中职网络安全B模块之国赛题远程代码执行渗透测试 PHPstudy的后门漏洞分析

2019 NeurIPS | Graph Convolutional Policy Network for Goal-Directed Molecular Graph Generation

如何在 Linux 上安装 MySQL

云服务器部署 Web 项目

R语言 第一部分

一、MySQL主从复制原理

MySQL 5.7 安装教程(全步骤、保姆级教程)
![mysql 数据去重的三种方式[实战]](/img/37/ad4007a32d9eb563a303756785e72f.png)
mysql 数据去重的三种方式[实战]

How on one machine (Windows) to install two MYSQL database

The first part of the R language
随机推荐
PowerCLi 一键批量部署OVA 到esxi 7
7/28-7/29 Expectation + thinking + suffix array + ST table
使用MySQL如何查询一年中每月的记录数
如何使用mysql binlog 恢复数据
关于@Autowired
"C language" frog jumping steps recursion problem
MySql 5.7.38下载安装教程 ,并实现在Navicat操作MySql
关于Error EPERM operation not permitted, mkdir...几种解决办法的比较
【云原生&微服务五】Ribbon负载均衡策略之随机ThreadLocalRandom
剑指offer-解决面试题的思路
期刊投递时的 Late News Submission 是什么
35-Jenkins-Shared library application
Ubuntu22.04安装mysql
mysql安装教程【安装版】
SSM框架简单介绍
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!
功能强大的国产Api管理工具
SQLAlchemy使用教程
[Cloud native] Introduction and use of Feign of microservices
The first part of the R language