LeetCode Divide Two Integers
来源:互联网 发布:复合增长率算法 编辑:程序博客网 时间:2024/05/24 06:51
Description:
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
Solution:
感觉用英文说不清了……哎……
是这样的,既然不能用乘除法,老夫的第一个反应是将被除数依次二分,dfs一下,这样有一个问题就是无法处理二分之后的+1 -1问题
既然二分,从上到下不好处理,那干脆就自下到上,将除数扩大到最大,然后再减法就好
具体描述一下
1. 将除数扩大,二分反过来就是乘以2,不过不用乘法,就用位运算 <<=1
2. 将除数扩大到小于被除数的最大数,准备阶段结束
3. 进入循环,循环条件就是除数大于等于最开始的除数初始值(divisor)以及被除数大于0
4. 每次循环都进行判断,如果a>b,那么就表示当前tot位是可以有一个的,也就是ans+=1l << tot;(这里的'l'保证是long类型的),a-=b
5. 然后每次循环都会将位数tot-1,b除以2
<span style="font-size:18px;">public class Solution {public int divide(int dividend, int divisor) {long a = dividend;long c = divisor, b = divisor;int flag = 1;if (a < 0) {a = -a;flag = -flag;}if (b < 0) {b = -b;c = -c;flag = -flag;}long ans = 0;int tot = 0;while (a > b) {if ((b << 1) > a)break;b <<= 1;tot++;}while (a > 0) {if (b < c)break;if (a >= b) {ans += 1l << tot;a = a - b;}b >>= 1;tot--;}ans = ans * flag;if (ans > Integer.MAX_VALUE)return Integer.MAX_VALUE;if (ans < Integer.MIN_VALUE)return Integer.MAX_VALUE;return (int) ans;}public static void main(String[] args) {Solution s = new Solution();System.out.println(s.divide(-2147483648, -1));}}</span>
这里换一个添加一个更加简洁的写法
<span style="font-size:18px;">public class Solution {public int divide(int dividend, int divisor) {int sign = 1;if (dividend < 0)sign = -sign;if (divisor < 0)sign = -sign;long a = Math.abs((long) dividend);long b = Math.abs((long) divisor);int move = 0;while (b << move < a)move++;long ans = 0l;while (move >= 0) {if ((b << move) <= a) {a -= (b << move);ans = ans + (1l << move);}move--;}ans = sign * ans;if (ans > Integer.MAX_VALUE)return Integer.MAX_VALUE;if (ans < Integer.MIN_VALUE)return Integer.MAX_VALUE;return (int) ans;}}</span>
0 0
- LeetCode: Divide Two Integers
- [LeetCode]Divide Two Integers
- LeetCode: Divide Two Integers
- [LeetCode] Divide Two Integers
- [Leetcode] Divide Two Integers
- LeetCode Divide Two Integers
- 【leetcode】Divide Two Integers
- [LeetCode]Divide Two Integers
- LeetCode-Divide Two Integers
- LeetCode: Divide Two Integers
- Divide Two Integers - leetcode
- Leetcode: Divide Two Integers
- LeetCode:Divide Two Integers
- leetcode Divide Two Integers
- LeetCode Divide Two Integers
- LeetCode | Divide Two Integers
- Leetcode: Divide Two Integers
- Divide Two Integers -- LeetCode
- 60.根据公式计算值
- 如何在城市中的股票下跌
- 关于Ui组件之WebView详解
- 关于不能将char** 类型转化为 const char**
- 支持向量机SVM(二)
- LeetCode Divide Two Integers
- Recognizer API
- Leetcode 219 Contains Duplicate II
- 程序实现自己删除
- Android 自定义View measure模板
- linux sort,uniq,cut,wc命令详解
- 二叉树相关公用方法
- linux键盘驱动详解等链接
- Android 自定义 HorizontalScrollView 横向滑动效果