๐๐ ๐ 29. ไธคๆฐ็ธ้ค
2022ๅนด10ๆ10ๆฅ
- algorithm
๐๐ ๐ 29. ไธคๆฐ็ธ้ค
้พๅบฆ: ๐๐ ๐
้ฎ้ขๆ่ฟฐ
่งฃๆณ
class Solution {
public int divide(int dividend, int divisor) {
// ๆ่ทฏ๏ผ
// ไธบ้ฒๆญข่พน็้ฎ้ข๏ผ็จ่ดๆฐไปฃๆฟๆญฃๆฐ่ฎก็ฎ
// ่ถ
่ๅคๆญ
int max = Integer.MAX_VALUE;
int min = Integer.MIN_VALUE;
if(dividend == min && divisor == -1) {
return max;
}
if(dividend == 0) {
return 0;
}
int flag = 1;
if((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0)) {
flag = -1;
}
// ๅฐๆญฃๆฐๅ
จ้จๅไธบ่ดๆฐ
if(dividend > 0) {
dividend = - dividend;
}
if(divisor > 0) {
divisor = - divisor;
}
// ่ฎก็ฎ
int res = 0;
while(dividend <= divisor) {
int tmp = divisor; // ๆพๅฐ dividend ่ฝๅค้ค็ๆๅคง้คๆฐ
int count = 1;
while(dividend - tmp <= tmp) {
// ่ฏดๆ tmp ๅฏไปฅๅขๅคงไธบๅๆฅ็ 2 ๅ
tmp += tmp;
count += count;
}
// tmp < dividend < 2*tmp
res += count;
dividend -= tmp; // ๆณจๆๆฏ่ดๆฐ็่ฟ็ฎ
}
if(flag == 1) {
return res;
} else {
return - res;
}
}
}