[LeetCode] Divide Two Integers

来源:互联网 发布:ubuntu怎么稳定翻墙 编辑:程序博客网 时间:2024/05/16 11:39

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

    

 这道题很有意思!

什么是除,除的结果是什么?

6 / 2 = 3 其实代表了6 = 2 + 2 + 2,即3个2相加,所以除其实是加的合并!


这里需要注意边界范围,long long 


class Solution {public:    int divide(int dividend, int divisor) {        int res = 0;        bool flag = false;        if ( (dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0) )        {            flag = true;        }        long long a = abs((long long)(dividend) );        long long b = abs((long long)(divisor) );                if (a < b)            return 0;                    while (a >= b)        {            long long temp = b;            int count = 1;            while (temp + temp < a)  //everytime double it to make the process fast!            {                temp += temp;                count += count;            }            //if the process make the divisor over the divident, miuse it            a = a - temp;            res += count;        }        if (flag == true)            return -res;        else             return res;    }};


0 0
原创粉丝点击