码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 29. Divide Two Integers

时间:2018-09-15 01:17:39      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:时间   a*   turn   +=   class   代码   integer   运行   public   

单纯减法不行,需要用到位运算。

a<<b表示 a*(2^b).

LeetCode出现了令人惊恐的同一段代码不同运行时间的情况.....

class Solution {
public:
    int divide(int x, int y) {
        int ans=0;
        if (x==INT_MIN && y==-1) return INT_MAX;
        
        long a=abs((long)x),b=abs((long)y);
        while(a>=b) {
            long m=1;
            long t=b;
            while((t<<1) <a){
                m<<=1;t<<=1;
            }
            a-=t;ans+=m;
        }
        
        if ((long)x*(long)y>0) return ans;
        else return -ans;
    }
};

 

LeetCode 29. Divide Two Integers

标签:时间   a*   turn   +=   class   代码   integer   运行   public   

原文地址:https://www.cnblogs.com/travelller/p/9649621.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!