Given a positive integer n, you can apply one of the following operations:
If n is even, replace n with n / 2.
If n is odd, replace n with either n + 1 or n - 1.
Return the minimum number of operations needed for n to become 1.
題目給咱一個正整數n,進行以下操作之一:
我的解題思路:
0. 先隨便設想一下,感覺大部分n是奇數的情況-1會比+1更有效率(後來發現影響不大)
0. 仔細想過後發現要讓n是4的倍數才是最有利的(可以至少連續除2兩次)
0. 數字變成3時一定要-1
class Solution {
public int integerReplacement(int n) {
int stp = 0;
while (n != 1) {
if (n % 2 == 0) {
n = n / 2;
} else {
// n是奇數
if ((n == 3) || ((n - 1) % 4 == 0)) {
n = n - 1;
} else {
n = n + 1;
}
}
stp++;
}
return stp;
}
}
修正一些小錯誤之後成功執行!