题目如下:
Given a positive integer n and you can do operations as follow:
- If n is even, replace n with
n/2
. - If n is odd, you can replace n with either
n + 1
orn - 1
.
What is the minimum number of replacements needed for n to become 1?
Example 1:
Input: 8 Output: 3 Explanation: 8 -> 4 -> 2 -> 1
Example 2:
Input: 7 Output: 4 Explanation: 7 -> 8 -> 4 -> 2 -> 1 or 7 -> 6 -> 3 -> 2 -> 1
UPDATE:
We have fixed the error in Integer Replacement. For input n = 3, the answer should be 2, not 3. Please try submitting again, thanks. We will rejudge your submissions after the contest finished and adjust your ranking accordingly.
这道题的主要思想其实是尽量减少-1和+1操作出现的次数,尽量多使用除2操作,这就要求中间环节的数字是偶数的次数多一些。所以,在每次进行+1或-1操作后我们会得到两个偶数。这时,我们就需要再对这个新的偶数进行一次除2操作,得到的数可能是奇数或者偶数(这取决于你之前选择的是+1操作还是-1操作,所以我们要都算一遍),我们最后会选择这个偶数进行下一次除2操作。已Accepted的代码如下所示:
public int integerReplacement(int n) {
int count = 0;
while(n!=1){
count++;
if(n%2==0){
n = n/2;
}else{
int temp1 = (n-1)/2;
int temp2 = temp1+1;
int temp = 0;
if(temp1%2==0 || temp1==1){
temp = temp1;
}else{
temp = temp2;
}
n = temp;
count++;
}
}
return count;
}
评论区地址在这里:
https://discuss.leetcode.com/category/521/integer-replacement,里面有其他使用递归和位运算的回答。