397. Integer Replacement

Given a positive integer n and you can do operations as follow:

 

  1. If n is even, replace n with n/2.
  2. If n is odd, you can replace n with either n + 1 or n - 1.

 What is the minimum number of replacements needed for n to become 1?

含义:给定一个正数n,如果n是偶数n/=2,如果n是奇数n= n + 1 or n - 1.求最少迭代次数使得n等于1

思路
利用bit位的操作。如果这个数偶数,那么末位的bit位一定是0。如果一个数是奇数,那么末位的bit位一定是1。对于偶数,操作是直接除以2。

对于奇数的操作:
如果倒数第二位是0(或者数字是011),那么n-1的操作比n+1的操作能消掉更多的1。
1001 + 1 = 1010
1001 - 1 = 1000
否则n+1的操作能比n-1的操作消掉更多的1。
1011 + 1 = 1100
10111 +  1 = 11000

还有一个tricky的地方是,为了防止integer越界,可以将n先转换成long。long N = n;这样的处理。

方法一:

 1     public int integerReplacement(int n) {
 2        if (n == Integer.MAX_VALUE) return 32; //n = 2^31-1;
 3         // 处理大数据的时候tricky part, 用Long来代替int数据
 4         long N = n;
 5         int count = 0;
 6         while(N != 1) {
 7             if(N % 2 == 0) {
 8                 N = N >> 1;
 9             }
10             else {
11                 // corner case;
12                 if(N == 3) {
13                     count += 2;
14                     break;
15                 }
16                 N = (N & 2) == 2 ? N + 1 : N - 1;
17             }
18             count ++;
19         }
20         return count;  
21     }

 

方法二:

 1     public int integerReplacement(int n) {
 2        if (n == Integer.MAX_VALUE) return 32; //n = 2^31-1;
 3         int count = 0;
 4         while (n > 1) {
 5             if (n % 2 == 0) n /= 2;
 6             else {
 7                 if ((n + 1) % 4 == 0 && (n - 1 != 2)) n++;
 8                 else n--;
 9             }
10             count++;
11         }
12         return count;
13     }

 

posted @ 2017-10-25 12:05  daniel456  阅读(129)  评论(0编辑  收藏  举报