leetcode29
不使用乘法、除法、求余数,计算两个数字相除。
使用加法和减法运算。
Java实现代码如下:
class Solution {
public int divide(int dividend, int divisor) {
if (dividend == Integer.MIN_VALUE && divisor == -) {
return Integer.MAX_VALUE;
}
long a = Math.abs((long)dividend);
long b = Math.abs((long)divisor);
int num = ;
long sum;
while (b <= a) {
sum = b;
int count = ;
while (sum + sum <= a) {
count += count;
sum += sum;
}
a = a - sum;
num = num + count;
}
if ((dividend < && divisor > ) || dividend > && divisor < ) {
num = -num;
}
return num;
}
}
上述代码用实际的例子进行解释,假设a=10,b=3,主要介绍10~19行的循环体的逻辑。
外部循环1:判断 3 <= 10满足
内部循环1.1:3 + 3 <= 10满足,count = 2,sum = 6
内部循环1.2:6 + 6 <= 10不满足,跳出内部循环,a = 10 - (3 + 3) = 4,num = 0 + 2 = 2
外部循环2:判断3 <= 4满足,
内部循环2.1:3 + 3 <= 4不满足,跳出内部循环,a = 4 - 3 = 1,num = 2 + 1 = 3。
最终num=3,即为所求。可分析,这里是计算在b的倍数,不超过a的情况下,最多是b的几倍。
用连续的加法来计算乘法,用减法来计算求余。
leetcode29的更多相关文章
- LeetCode29 Divide Two Integers
题目: Divide two integers without using multiplication, division and mod operator. If it is overflow, ...
- [Swift]LeetCode29. 两数相除 | Divide Two Integers
Given two integers dividend and divisor, divide two integers without using multiplication, division ...
- LeetCode29.两数相除 JavaScript
给定两个整数,被除数 dividend 和除数 divisor.将两数相除,要求不使用乘法.除法和 mod 运算符. 返回被除数 dividend 除以除数 divisor 得到的商. 示例 1: 输 ...
- 算法练习--LeetCode--29. Divide Two Integers
Divide Two Integers Given two integers dividend and divisor, divide two integers without using multi ...
- leetcode-29.两数相除(不用乘除法和mod)
如题,不用乘除法和mod实现两数相除. 这里引用一位clever boy 的解法. class Solution { public: int divide(int dividend, int divi ...
- LeetCode29 Medium 不用除号实现快速除法
本文始发于个人公众号:TechFlow,原创不易,求个关注 链接 Divide Two Integers 难度 Medium 描述 给定两个整数,被除数和除数,要求在不使用除号的情况下计算出两数的商 ...
- leetcode29 两数相除 int 与移位
难受啊 考虑越界 考虑dividend为-2^31,用负数移位运算 class Solution { public: int divide(int dividend, int divisor) { i ...
随机推荐
- 网卡驱动_WDS
参考 cs89x0.c 1.网卡驱动程序与网络驱动程序的区别网卡驱动程序:网络驱动程序中最底层的驱动,主要工作:把上面发下来的数据发送出去,收到数据后构造一个包抛给上层.有收发能力就可以了. 2.网卡 ...
- stardog graphql 简单操作
预备环境: 下载stardog 软件包 graphql 查询地址 创建一个简单数据库 ./stardog-admin db create -nstarwars graphql 查询方式 http 地址 ...
- PHP独立环境搭建细节
一.安装前准备: 准备安装软件此处以以下软件为例: Appache:httpd-2.2.21-win32-x86-openssl-0.9.8r.msi MySQL: mysql-5.5.21-win ...
- POJ_2299 Ultra-QuickSort【归并排序】
版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/u013912596/article/details/35655703 题目链接:http://poj ...
- MapReduce-线性回归
线性回归有是三个值很重要: 1. 斜率 2. 截距:x和y轴的交点值: 3. 显著性:数据偏离线性的程度,用以判断数据可以用线性表示的程度:拟合度 apache.commons.math3里面有一 ...
- VS2010程序调试
http://blog.csdn.net/kingzone_2008/article/details/8133048 调试初识及实例.
- Asp.Net中使用Newtonsoft.Json转换,读取,写入
using Newtonsoft.Json;using Newtonsoft.Json.Converters; //把Json字符串反序列化为对象目标对象 = JsonConvert.Deserial ...
- c#数据类型 与sql的对应关系 以及 取值范围
Short Name .NET Class Type Width Range (bits) SQL Datatype (Closest Match) Constraint to use (if nee ...
- bzoj 3795: 魏总刷DP
Description 魏总,也就是DP魏又开始刷DP了.一共有n道题,第i道题魏总原本需要u[i]秒的时间.不过,为了表达对这些水题的藐视,魏总决定先睡k秒再开始刷题.魏总并不清楚自己会睡多久,只知 ...
- 安全测试chicklist