Leetcode 397.整数替换

整数替换

给定一个正整数 n,你可以做如下操作:

1. 如果 是偶数,则用 n / 2替换 n
2. 如果 是奇数,则可以用 n + 1或n - 1替换 n
变为 1 所需的最小替换次数是多少?

示例 1:

输入:

8

 

输出:

3

 

解释:

8 -> 4 -> 2 -> 1

示例 2:

输入:

7

 

输出:

4

 

解释:

7 -> 8 -> 4 -> 2 -> 1

7 -> 6 -> 3 -> 2 -> 1

 1 import static java.lang.Math.min;
 2 
 3 class Solution {
 4     int integerReplacement(int n)
 5     {
 6         if(n == Integer.MAX_VALUE)
 7             return 32;
 8         if(n <= 1)
 9             return 0;
10         if((n & 1) == 0)
11             return 1 + integerReplacement(n / 2);
12         else
13             return 1 + min(integerReplacement(n - 1), integerReplacement(n + 1));
14     }
15 }

猜你喜欢

转载自www.cnblogs.com/kexinxin/p/10235397.html