397. Integer Replacement
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?
Example 1:12345678Input:8Output:3Explanation:8 -> 4 -> 2 -> 1
Example 2:12345678910Input:7Output:4Explanation:7 -> 8 -> 4 -> 2 -> 1or7 -> 6 -> 3 -> 2 -> 1
Bit Manipulation
Ref: https://discuss.leetcode.com/topic/58334/a-couple-of-java-solutions-with-explanations
这个题目标的难度是easy, 但是做起来完全没有那么easy。不太好想到。
- n 是偶数,n = n / 2
- n 是奇数,就要判断什么时候+1好,什么时候-1好。
- 若n的最低两位数为01,则令n = n - 1
- 若n的最低两位数为11,则令n = n + 1
- 这样处理是为了使n的二进制表式中1的数目尽可能少,从而减少迭代次数
- 需要注意的是,当n = 3时,不满足上述判定条件,需要单独处理。
|
|
递归
|
|