Skip to content

Latest commit

 

History

History
75 lines (54 loc) · 1.68 KB

397-integer-replacement.md

File metadata and controls

75 lines (54 loc) · 1.68 KB

397. Integer Replacement - 整数替换

给定一个正整数 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

题目标签:Bit Manipulation / Math

题目链接:LeetCode / LeetCode中国

题解

Language Runtime Memory
cpp 0 ms 774.1 KB
class Solution {
public:
    int integerReplacement(int n) {
        int res = 0;
        long long x = (long long)n;
        for (; x != 1; res++) {
            // Note: the priority of & is lower than ==
            if ((x & 1) == 0) {
                x >>= 1;
            } else if (x == 3 || (x & 3) == 1) {
                x--;
            } else {
                x++;
            }
        }
        return res;
    }
};
static auto _ = [](){ ios::sync_with_stdio(false); cin.tie(nullptr); return 0; }();