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 @   daniel456  阅读(131)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示