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 or n - 1.
What is the minimum number of replacements needed for n to become 1?
class Solution {
public:
int integerReplacement(int n) {
int i=0;
long long a=n;
while(a>1)
{
if(a%2==0)
a=a/2;
else if(((a-1)/2)%2==0||((a-1)/2)==1)
a=a-1;
else if(((a+1)/2)%2==0||((a+1)/2)==1)
a=a+1;
i=i+1;
}
return i;
}
};
思想:
主要思想就是说加入n是偶数,那么肯定是要除以二2的,假如是奇数,那么考虑除以二后是偶数还是奇数,而且是先考虑n-1的情况而非n+1的情况。两者之间比较,若有一个是除以二后还是偶数的情况,那么它会比较快。还要注意用long long就不怕2147483647这个int型最大数溢出了。