divide-two-integers

https://www.nowcoder.com/practice/472c6e8772bd4f1299fbe4a60f3b54f7?tpId=46&tqId=29150&tPage=1&rp=1&ru=/ta/leetcode&qru=/ta/leetcode/question-ranking

思路:除数成倍的减少,统计减少多少次

class Solution {
public:
    int divide(int dividend, int divisor) {
		//取绝对值转化为正整数
		long long  a = abs((long long )dividend);
		long long b = abs((long long )divisor);
		long long  res = 0;//统计除数减的次数
		while(a >= b){
			long long  sum = 1;
			long long  tmp = b;
			while(tmp + tmp<= a){
				tmp = tmp + tmp;//tmp*2 成倍加
				sum = sum + sum;//sum*2 同理
			}
			res += sum;//次数加
			a -= tmp;//统计剩余的a

		}

		//右移获得符号位
		return (dividend >> 31 ) ^ (divisor >> 31) ?  -res : res;
	}
};

 

你可能感兴趣的:(Leetcode)