[Leetcode] Divide Two Integers (Java)
2013-12-28 18:00
295 查看
Divide two integers without using multiplication, division and mod operator.
输入两个整数,dividend, divisor,不要使用乘法,除法,取模运算,求出a/b的值。
如果每次减divisor,会超时,让sum=b,每次sum翻倍,然后count也翻倍,效率会高点儿
输入两个整数,dividend, divisor,不要使用乘法,除法,取模运算,求出a/b的值。
如果每次减divisor,会超时,让sum=b,每次sum翻倍,然后count也翻倍,效率会高点儿
public class DivideTwoIntegers { public int divide(int dividend, int divisor) { int res=0; if(dividend==0||divisor==0) return 0; boolean flag = true; if((dividend>0&&divisor<0)||(dividend<0&&divisor>0)) flag = false; long a = Math.abs((long)dividend); long b = Math.abs((long)divisor); long sum; int count; while(a>=b){ sum = b; count = 1; while(sum+sum<=a){ count+=count; sum+=sum; } a-=sum; res+=count; } return flag?res:-res; } public static void main(String[] args) { int dividend = 1; int divisor = 1; System.out.println(new DivideTwoIntegers().divide(dividend, divisor)); } }
相关文章推荐
- (LeetCode) Divide Two Integers (Java)思路讲解及实现
- Java for LeetCode 029 Divide Two Integers
- [LeetCode-Java]29. Divide Two Integers
- Java [leetcode 29]Divide Two Integers
- (Java)LeetCode-29. Divide Two Integers
- 【LeetCode-面试算法经典-Java实现】【029-Divide Two Integers(两个整数相除)】
- LeetCode : Divide Two Integers [java]
- Divide Two Integers leetcode java
- LeetCode 29 Divide Two Integers (C,C++,Java,Python)
- [LeetCode]Divide Two Integers
- leetcode 29 divide two integers
- [LeetCode]29. Divide Two Integers
- 【leetcode】Divide Two Integers
- leetcode 29: Divide Two Integers
- leetcode第28题--Divide Two Integers
- [LeetCode] Divide Two Integers
- LeetCode 29. Divide Two Integers(整数除法)
- [leetcode] 29. Divide Two Integers 解题报告
- Leet Code 29 Divide Two Integers - 两个整数相除 - Java
- 【leetcode-29】Divide Two Integers(C)