当前位置: 首页 > news >正文

剑指Offer(数据结构与算法面试题精讲)C++版——整数除法

1、面试题1:整数除法

题目:
在这里插入图片描述

解法1:暴力法,直接连减,时间复杂度:O(n):

#include <bits/stdc++.h>
using namespace std;
int devide(int dividend,int divisor) {
	int result=0;
	//注意这里的存在溢出,整数范围:-2^31-2^31-1
	if(dividend==0x80000000&&divisor==-1) {
		return INT_MAX;
	}
	while(dividend>divisor) {
		dividend-=divisor;
		result++;
	}
	return result;
}
int main() {
	cout<<devide(15,2);
}

解法2:仿二分法,每次找2倍乘最接近于被除数的数,然后减去该数,原书说这里的时间复杂度为O(logn),但是其实只是找到了最接近的减数;最坏情况下,如果这里的被除数为n=2^m-1=1+2+4+…+2^(m-1),除数为1,内层循环查找依次对应m-1,m-2,…,2,1,总时间复杂度为:O(m^2),由即m=log2(n+1),从而时间复杂度为O2(logn),也能够起到优化作用。

#include <bits/stdc++.h>
using namespace std;
int devide(int dividend,int divisor) {
	const int low_limit=0xc0000000,high_limit=0x40000000;
	int result=0;
	//注意这里的存在溢出,整数范围:-2^31-2^31-1
	if(dividend==INT_MIN&&divisor==-1) {
		return INT_MAX;
	}
	while(dividend>=divisor) {
		int tmp=divisor;
		int times=1;
		//应满足 tmp>= -2^30,防止tmp+tmp负向溢出 
		//且应满足 tmp<*2^30, 防止tmp+tmp正向溢出 
		while((tmp>=low_limit) && (tmp<high_limit) && (dividend>=tmp+tmp)) {
			tmp+=tmp;
			times+=times;
		}
		result+=times;
		dividend-=tmp;
	}
	return result;
}
int main() {
	cout<<devide(15,2);
}

在这里插入图片描述

http://www.dtcms.com/a/102437.html

相关文章:

  • 【Keepalived】Keepalived-2.3.3明确结束对CentOS 7的支持
  • 【蓝桥杯】第十四届C++B组省赛
  • git 常用操作整理
  • L1-083 谁能进图书馆(10分)(超详解)
  • 优化 ant-select(下拉数据太多)导致的页面卡顿问题
  • MPLAB X IDE 环境中配置字的注意点
  • python的sys中sys.argv 和 sys.exit() 用法
  • 数据层的基本操作
  • RKNN SDK User Guide学习要点
  • .NET 调用API创建系统服务实现权限维持
  • 实现ESP32woor连接deepseek进行访问
  • 【 <二> 丹方改良:Spring 时代的 JavaWeb】之 Spring Boot 中的安全性:使用 Spring Security 实现认证与授权
  • React 中的 Props
  • 文件操作与IO—文件读写
  • 开源手机号码价值评估系统
  • AI Agent系列(八) -基于ReAct架构的前端开发助手(DeepSeek)
  • Spring笔记04-注解注入
  • Python每日一题(11)
  • oracle执行计划
  • 《异常检测——从经典算法到深度学习》30. 在线服务系统中重复故障的可操作和可解释的故障定位
  • 42. 接雨水
  • Flutter敏感词过滤实战:基于AC自动机的高效解决方案
  • 二分查找:原理、循环不变量与边界处理
  • 设置网站主题色color-scheme
  • 【Easylive】HttpServletRequest、HttpServletResponse、HttpSession 介绍
  • Leetcode hot 100刷题之路(day 1)
  • 黑盒测试的场景法(能对项目业务进行设计测试点)
  • ngx_monotonic_time
  • Git Fetch 和 Git Pull 的区别
  • 双层板模组天线设计指南,50欧姆阻抗匹配设计