1. 程式人生 > >LeetCode29 兩數相除

LeetCode29 兩數相除

相當於複雜度優化到logN.
如 100 3
普通方法是 3 + 3 + 3 + 3 … + 3累加到100,數加了多少次
優化方法 3 6 12 24…
1 2 4 8… 看能累加多少次,超過的方法減去求得剩下的值,繼續進行累加。
注意邊界條件

package 牛客刷題.LeetCode.模擬.divide_two_integers;

/**
 * Created by Administrator on 2018/5/26 0026.
 */
public class Solution {
    public static void main(String[] args) {
        //System.out.println(divide(Integer.MIN_VALUE, -1));
//System.out.println(divide(8, 1)); //System.out.println(divide(24,3)); System.out.println(divide(-1010369383 ,-2147483648)); } public static int divide(int dividend, int divisor) { if (dividend == Integer.MIN_VALUE && divisor == -1) { return Integer.MAX_VALUE; } long
a = Math.abs((long)dividend); long b = Math.abs((long)divisor); int num = 0; long sum; while (b <= a) { sum = b; int count = 1; while (sum + sum <= a) { count += count; sum += sum; } a = a - sum; num = num + count; } if
((dividend < 0 && divisor > 0) || dividend > 0 && divisor < 0) { num = -num; } return num; } }