leetcode 29
来源:互联网 发布:舟山淘宝代运营诈骗案 编辑:程序博客网 时间:2024/05/22 03:47
题意: 不用乘法和除法,以及取余,实现两个数的除法。如果溢出返回MAX_INT
思路:让除数以2倍关系递增,然后直到刚好超过被除数,在递增过程中保存除数递增的每个结果到一个数组里,并且保存刚好超过时的数组下标Max,数组的下标i就代表着这是2的i次方个除数,那么从遍历Max-0,累加,如果累加中某一个和值大于了被除数,不加这个数,继续下一个,不大于则加上,为了无限靠近。因为我们都知道2^1 + 2^2 + … + 2^(n-1) = 2^n-1这个公式。累加过程中我们要同时累加数组下标代表的除数个数。最后返回即可。
代码:
class Solution {
public:
int divide(int dividend, int divisor) {
if(dividend == -2147483648 && divisor == -1){
return 2147483647;
}
static long long int array[40];
long long a = llabs((long long)dividend);
long long b = llabs((long long)divisor);
int ret = 0;
long long sum = 0;
int i = -1;
while(b <= a){
array[++i] = b;
b <<= 1;
}
for(int j = i; j >= 0; j--){
if(sum+array[j] > a){
continue;
}else{
sum += array[j];
ret += pow(2, j);
}
}
if((dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0)){
return -ret;
}else{
return ret;
}
}
};
- leetcode 29
- [LeetCode] Distinct Subsequences [29]
- leetCode(29):Happy Number
- leetcode #29 in cpp
- leetCode练习(29)
- 2017.10.29 LeetCode
- LeetCode刷题(29)
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- WebSokcet
- Hdu 1312 Red and Black 深搜
- hdu 5900 QSC and Master 区间dp
- [经验]tableview的contentSize默默自己在变。
- SSLHandshakeException: Received fatal alert: handshake_failure
- leetcode 29
- Java基础之运算符
- 数值分析常用的几个小程序C++实现
- 51nod 1201 整数划分(dp)
- cordova开发教程
- NandFlash ECC 校验算法原理与实现
- android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a vi
- Android打开系统相册页面
- 一些小知识点