Leetcode || Divide Two Integers
来源:互联网 发布:空间数据库 吴信才ppt 编辑:程序博客网 时间:2024/06/04 19:16
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
看了网上的拆分思路,逻辑写出来是不难的,但-2147483648/1和-2147483648/-1是难点
package pack;class Solution { public int divide(int dividend, int divisor) { return (int)divideL(dividend, divisor); //如果不用去long里面做,-2147483648/1很难解决 } /*例如计算:87/4 * 87=4*2^4+4*2^2+4*2^1 * 87=4*(2^4+2^2+2^1) ,而括号里的数就是我们要求的结果 * 可以每次将除数4左移1位(乘以2),到了接近被除数87时就停止, * result先加上2^4,被除数减去,再下一次执行while体语句 */ public static long divideL(long dividend,long divisor){ int flag = 0; if(divisor == 0 ) return Integer.MAX_VALUE; if(Math.abs(dividend) <Math.abs(divisor) || dividend==0 ) return 0; if(dividend < 0 && divisor<0) { long a = divideL(Math.abs(dividend),Math.abs(divisor)); if(a==2147483648L) //特殊情况:-2147483648/-1,要返回Integer.MAX_VALUE return Integer.MAX_VALUE; else return a; } if(dividend < 0 && divisor>0) return -divideL(Math.abs(dividend),Math.abs(divisor)); if(dividend > 0 && divisor<0) return -divideL(Math.abs(dividend),Math.abs(divisor)); long tmp = 0L; //不加L的话,默认存储格式为int(为了省空间),会溢出 long tmp_divisor = divisor; long result = 0L; while(dividend>0) { long count = 0; tmp_divisor = divisor; //被除数每次要减,除数不能变,增个副本 while(tmp_divisor<=dividend) { tmp_divisor <<= 1; count++; //记下左移次数 } if(count==0) return result; tmp = divisor <<(count-1); //不光result定义时强调是L,1后面一定要加L,不分配那样长的内存,怎么左移那么多位 result += 1L << (count-1); //result += (long)Math.pow(2, (count-1)); dividend -= tmp; } return result; }}public class Mian { public static void main(String[] args) { System.out.println(new Solution().divide(-2147483648,1)); }}
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
- Whatsapp like Image Compression in Android with demo Ambalika Saha June 28, 2013
- C# winform与Javascript的相互调用
- 方便好使的java.util.Properties类
- Linux的资源管理器
- Android的AlertDialog点击确认键dialog不消失
- Leetcode || Divide Two Integers
- php封装操作数据库的类
- Word 编辑技巧平时总结
- 系统吞吐量、TPS(QPS)、用户并发量、性能测试概念和公式
- java 获取本月第一天,和获取上个月的最后一天
- 最长递增子序列问题的求解
- 常用正则表达式
- 关于android 字间距的问题
- C# winform与Javascript的相互调用