Posts Tagged 【Math】

来源:互联网 发布:知乎led灯化妆镜 编辑:程序博客网 时间:2024/05/16 13:40

Divide Two Integers

 Total Accepted: 34460 Total Submissions: 225991My Submissions

Divide two integers without using multiplication, division and mod operator.

If it is overflow, return MAX_INT.

//Submission Result: Time Limit Exceededpublic class Solution {    public long divide(int dividend, int divisor) {    if(divisor == 0) return Integer.MAX_VALUE;    int dividendAbs = Math.abs(dividend);        long sum = Math.abs(divisor), i = 0,getValue = 1;        while(sum<=dividendAbs) {            sum+=sum;            i++;        }        if(i == 0) return 0;        getValue<<=--i;        sum>>=1;        while(sum < dividendAbs) {            getValue++;        sum+=divisor;        }        if(sum>dividendAbs) getValue--;        return (dividend <= 0 && divisor >0 || dividend >= 0 && divisor <0) == true?-getValue:getValue;    }}





Have you met this question in a real interview?
0 0
原创粉丝点击