【leetCode】29_两数相除

class Solution {
    int temp, length;

    public int divide(int dividend, int divisor) {

        Boolean tag = divisor > 0 && dividend > 0 || divisor < 0 && dividend < 0;
        int adividend = dividend > 0 ? -dividend: dividend;
        int adivisor = divisor > 0 ? -divisor: divisor;
        
        if (dividend == 0x80000000 && divisor == 0x80000000)
            return 1;
        int ans = divid(adividend, adivisor);

        return !tag ? ans:(~ans+1 < 0 ? 0x7fffffff: ~ans + 1);
    }

    int divid(int dividend, int divisor){
        StringBuffer ans = new StringBuffer();
        ans.append('-');
        String did = String.valueOf(dividend);
        if (dividend > divisor)
            return 0;
        temp = 0;
        length = String.valueOf(dividend).length();
        for (int i = 1; i < length; i ++){
            long tt= temp;
            temp = temp << 2;
            temp += tt;
            //System.out.println(tt);
            temp = temp << 1;
            temp += -(did.charAt(i) - '0');
            if (temp > divisor){
                if (ans.length() > 1){
                    ans.append('0');
                }
                continue;
            }
            int t = 0;
            while(temp - divisor <= 0){
                t += 1;
                temp -= divisor;
            }
            ans.append((char)('0' + t));
        }

        int t = Integer.parseInt(ans.toString());
        return t;
    }
}

 

你可能感兴趣的:(leetCode)