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

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 }