Divide Two Integers

 https://leetcode.com/problems/divide-two-integers/

https://www.interviewbit.com/courses/programming/topics/bit-manipulation/ 


43/8

43=8*5+3

43=8*pow(2,2)+8*pow(2,0)+3

43=8[pow(2,2)+pow(2,0)]+3

1<<2 +1<<0=5

1<<i=1*2^i

k<<i=k*2^i


 class Solution {
public:
    int divide(int x, int y) {
        long long int a=x,b=y;
        int sign=0;
        if((a>0 && b<0) || (a<0 && b>0)) sign=1;
        if(a<0) a=-a;
        if(b<0) b=-b;
        long long int ans=0,temp=0;
        for(int i=31;i>=0;i--){
            if(temp+(b<<i)<=a){
                temp+=b<<i;
                ans+=1ll<<i;
            }
        }
        if(sign==1) ans=-ans;
        if(ans>INT_MAX || ans<INT_MIN)  return INT_MAX;
        return ans;
    }
};

Comments

Popular posts from this blog

Perfect Peak of Array

Is Rectangle?

Sort array with squares!