aboutsummaryrefslogtreecommitdiff
path: root/store/works/solutions/leetcode/cpp/397.cpp
blob: bbb61ff576433e18489152828f3c6c2b5d1ed8f3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Solution
{
public:
    int integerReplacement(int n)
    {
        if (n == 2147483647)
            return 32;

        int count = 0;

        while (n != 1)
        {
            if (n == 2)
            {
                count += 1;
                break;
            }
            if (n == 3)
            {
                count += 2;
                break;
            }
            if (n % 2 == 0)
            {
                count += 1;
                n /= 2;
                continue;
            }
            if ((n - 1) % 4 == 0)
            {
                count += 3;
                n = (n - 1) / 4;
                continue;
            }
            if ((n + 1) % 4 == 0)
            {
                count += 3;
                n = (n + 1) / 4;
                continue;
            }
            count += 2;
            n = (n - 1) / 2;
        }

        return count;
    }
};