feat: 2025-10-28打卡
This commit is contained in:
44
29.divide-two-integers.java
Normal file
44
29.divide-two-integers.java
Normal file
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* @lc app=leetcode id=29 lang=java
|
||||
*
|
||||
* [29] Divide Two Integers
|
||||
*/
|
||||
|
||||
// @lc code=start
|
||||
class Solution {
|
||||
public int divide(int dividend, int divisor) {
|
||||
long x = Math.abs((long)dividend),
|
||||
y = Math.abs((long)divisor);
|
||||
long r = 0;
|
||||
while(true) {
|
||||
long[] t = floor(x, y);
|
||||
if(t[0] == 0) {
|
||||
break;
|
||||
}
|
||||
x -= t[1];
|
||||
r += t[0];
|
||||
}
|
||||
int sign = (dividend>=0?1:-1) * (divisor>=0?1:-1);
|
||||
r = r * sign;
|
||||
return (int)Math.max(Math.min(r, Integer.MAX_VALUE), Integer.MIN_VALUE);
|
||||
|
||||
}
|
||||
|
||||
private long[] floor(long x, long y) {
|
||||
if(x <= y) {
|
||||
return x == y ? new long[]{1, y}:new long[]{0, 0};
|
||||
}
|
||||
long s = y;
|
||||
long r = 1;
|
||||
while(true) {
|
||||
if(s + s > x) {
|
||||
break;
|
||||
}
|
||||
s = s + s;
|
||||
r = r + r;
|
||||
}
|
||||
return new long[] {r, s};
|
||||
}
|
||||
}
|
||||
// @lc code=end
|
||||
|
||||
Reference in New Issue
Block a user