397. Integer Replacement
做题历程:
- 2016/oct/22,本题是第一次做,独立解出,耗时10分钟、
本题难度还是比较低的,更像是一道Easy而不是Medium。
本题我最开始涌出了很多想法,不过发现都不好用。。最后决定就是用recursive解就可以,还是比较简单的。。
代码如下:
class Solution {
public:
int integerReplacement(int n) {
if (n == 1) {
return 0;
}
if (n == INT_MAX) {
return 2 + integerReplacement((n - 1) / 2 + 1);
}
if (n % 2 == 0) {
return 1 + integerReplacement(n / 2);
}
else {
return 1 + min(integerReplacement(n - 1), integerReplacement(n + 1));
}
}
};