[leetcode] Divide Two Integers

임택·2021년 2월 28일
0

알고리즘

목록 보기
42/63

problem

code

  • idea:
    A = e^logA
    LogA/B = LogA - LogB
  • application: A/B = e^LogA/B = e^(LogA - LogB)
class Solution {
    public int divide(int A, int B) {
        int ans = 0;
        if (B == -2147483648) return A == B ? 1 : 0;
        if (A == -2147483648) {
            if (B == 1) return -2147483648;
            if (B == -1) return 2147483647;
          	// A = -2147483648, B = -1000 => 2147483.648
          	// A = -2147483648, B = 1000 => -2147483.648
            System.out.println(">> " + Math.abs(A)); 
            // print: -2147483648; Math.abs does not work 
            // cuz there is no way to express 2147483648 lol
            A += Math.abs(B);
            ans++;
            
        }
        ans += 
          Math.floor(
            Math.exp(
              Math.log(Math.abs(A)) - Math.log(Math.abs(B))
            )
        );
        return A > 0 == B > 0 ? ans : -ans;
    }
}
profile
캬-!

0개의 댓글