给定一个正整数n
,你可以做如下的操作:
- 如果
n
为偶数,将n
替换为n/2
。 - 如果
n
为奇数,你可以将n
替换为n + 1
或n - 1
。
将n
转换为1
的最少的替换次数为多少?
样例
样例1:
输入:
8
输出:
3
说明:
8 -> 4 -> 2 -> 1
样例2:
输入:
7
输出:
4
说明:
7 -> 8 -> 4 -> 2 -> 1
or
7 -> 6 -> 3 -> 2 -> 1
class Solution {
public:
/**
* @param n: a positive integer
* @return: the minimum number of replacements
*/
int integerReplacement(int n) {
// Write your code here
return times(n);
}
long long times(long long n)
{
if(n <= 1)
return 0;
else if(n == 2)
return 1;
else if(n == 3)
return 2;
if((n % 2) == 0)
return times(n / 2)+1;
long long min1 = times(n+1)+1;
long long min2 = times(n-1)+1;
return min(min1,min2);
}
};