标签:class blog code java http tar
Divide two integers without using multiplication, division and mod operator.
https://oj.leetcode.com/problems/divide-two-integers/
思路1:看样只能用减法了,依次减去除数,TOTS,肯定超时。
思路2:每次减去N倍的除数,结果也加上N次,因此我们需要将除数扩大N倍。
public class Solution { public int divide(int dividend, int divisor) { if (dividend == 0 || divisor == 1) return dividend; long divid = dividend; long divis = divisor; boolean neg = false; int result = 0; if (dividend < 0) { neg = !neg; divid = -divid; } if (divisor < 0) { neg = !neg; divis = -divis; } long[] multi = new long[32]; for (int i = 0; i < 32; i++) multi[i] = divis << i; for (int i = 31; i >= 0; i--) { if (divid >= multi[i]) { result += 1 << i; divid -= multi[i]; } } return (neg ? -1 : 1) * result; } public static void main(String[] args) { System.out.println(new Solution().divide(5, 2)); System.out.println(new Solution().divide(5, -2)); System.out.println(new Solution().divide(100, 2)); System.out.println(new Solution().divide(222222222, 2)); System.out.println(new Solution().divide(-2147483648, 2)); } }
参考:
http://blog.csdn.net/doc_sgl/article/details/12841741
http://blog.csdn.net/linhuanmars/article/details/20024907
[leetcode] Divide Two Integers,布布扣,bubuko.com
[leetcode] Divide Two Integers
标签:class blog code java http tar
原文地址:http://www.cnblogs.com/jdflyfly/p/3810717.html