Problems
经典题目
For example, dividend = 15, divisor = 2
Each time, we try to remove k(max) times of divisor(2) from dividend(15), where k * divisor <= dividend.
First time, 15 - divisor 2 2 = 7
Then, 7 - divisor * 2 = 3
Then, 3 - divisor = 1
public int divide(int dividend, int divisor) {
// corner case
if (dividend == Integer.MIN_VALUE && divisor == -1) return Integer.MAX_VALUE;
if (dividend == 0) return 0;
boolean isPos = ((dividend > 0 && divisor > 0) || (dividend < 0 && divisor < 0)) ? true : false;
int res = 0;
long dvd = Math.abs((long) dividend);
long dvs = Math.abs((long) divisor);
while (dvs <= dvd) {
long tmp = dvs, multiple = 1;
while (dvd >= (tmp << 1)) {
tmp <<= 1;
multiple <<= 1;
}
dvd -= tmp;
res += multiple;
}
return isPos ? res : -res;
}First, we observe that for any given sequence that is in descending order, no next larger permutation is possible.
We need to find the first pair of two successive numbers a[i] and a[i - 1], from the right, which satisfy a[i] > a[i - 1]. Now, all numbers to the right of a[i - 1] are in descending order, which means no larger permutations is possible for that sequence. So we need to increment a[i - 1] and we need to pick one number from a[i] to a[nums.length - 1] to replace with a[i - 1]. That would be the first number greater than a[i - 1] from the right. Then after the replacement, all the numbers to the right of a[i - 1] still remain descending. So finally, we need to reverse all the numbers from a[i] to a[nums.length - 1].
num[i] * num[j] will be placed at indices i + j and i + j + 1
首先,两点确定一条直线。如果用斜率,则需要一个点和一个斜率。
所以,我们可以先确定一个点,再找另一个点,看在同一直直线上有多少个点。
需要注意的是,1. 相同的点的时候,即 same X && same Y。2. 直线斜率不存在的时候,即 same Y。3. 一般情况。
166 Fraction to Recurring Decimal
处理无理数时,keep 一个 hashmap,防止出现无限循环小数
处理overflow时,比如-2147483648 / -1,-1 / -2147483648,转换成Long类型
Because all trailing zeroes are from factors 2 * 5. We just need to count how many 5s out there. But some number have multiple 5s, like 25 have 2, and 125 have 3, etc.
Mark all the evens, multiples of 3, multiples of 5, etc. as true. Then just count how many false are there.
Last updated