1. 程式人生 > >397.整數替換

397.整數替換

給定一個正整數 n,你可以做如下操作:

1. 如果 是偶數,則用 n / 2替換 n
2. 如果 是奇數,則可以用 n + 1n - 1替換 n
變為 1 所需的最小替換次數是多少?

示例 1:

輸入:8
輸出:3
解釋:8 -> 4 -> 2 -> 1

示例 2:

輸入:7
輸出:4
解釋:7 -> 8 -> 4 -> 2 -> 1或7 -> 6 -> 3 -> 2 -> 1

class Solution {
public:
    int integerReplacement(int n) {
        if (n == 1) return 0;
        if (n % 2 == 0) return 1 + integerReplacement(n / 2);
        else {
            long long t = n;
            return 2 + min(integerReplacement((t + 1) / 2), integerReplacement((t - 1) / 2));
        }
    }
};