博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
397. Integer Replacement
阅读量:5036 次
发布时间:2019-06-12

本文共 1900 字,大约阅读时间需要 6 分钟。

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?

 

Example 1:

Input:8Output:3Explanation:8 -> 4 -> 2 -> 1

 

Example 2:

Input:7Output:4Explanation:7 -> 8 -> 4 -> 2 -> 1or7 -> 6 -> 3 -> 2 -> 1

 

Approach #1: Math. [Java]

class Solution {    public int integerReplacement(int n) {        int c = 0;        while (n != 1) {            if ((n & 1) == 0) n >>>= 1;            else if (n == 3 || ((n >>> 1) & 1) == 0) n--;            else n++;            c++;        }        return c;    }}

  

Analysis:

The first step towards solution is to realize that you're allowed to remove the LSB only if it's zero. And to reach the target as far as possible, removing digits is the best way to go. Hence, even numbers are better than odd. This is quite obvious.

What is not so obvious is what to do with odd numbers. One may think that you just need to remove as many 1's as possible to increase the evenness of the number. Wrong! Look at this example:

111011 -> 111010 -> 11101 -> 11100 -> 1110 -> 111 -> 110 -> 11 -> 10 -> 1

And yet, this is not the best way because

111011 -> 111100 -> 11110 -> 1111 -> 10000 -> 1000 -> 100 -> 10 -> 1

Both 111011 -> 111010 and 111011 -> 111100 remove the same number of 1's, but the second way is better.

So, we just need to remove as many 1's as possible, doing +1 in case of a tie? Not quite. The infamous test with n = 3 fails for that stratefy because 11 -> 10 -> 1 is better than 11 -> 100 -> 10 -> 1. Fortunately, that's the only exception (or at least I can't think of any other, and there are none in the tests).

So the logic is:

If n is even, halve it.

If n = 3 or n - 1has less 1's than n+1, decrement n.

Otherwise, increment n.

 

Reference:

 

转载于:https://www.cnblogs.com/ruruozhenhao/p/10816078.html

你可能感兴趣的文章
RijndaelManaged 加密
查看>>
Android 音量调节
查看>>
HTML&CSS基础学习笔记1.28-给网页添加一个css样式
查看>>
windows上面链接使用linux上面的docker daemon
查看>>
Redis事务
查看>>
Web框架和Django基础
查看>>
python中的逻辑操作符
查看>>
CSS兼容性常见问题总结
查看>>
HDU 1548 A strange lift (Dijkstra)
查看>>
每天一个小程序—0005题(批量处理图片大小)
查看>>
C# 启动进程和杀死进程
查看>>
tcp实现交互
查看>>
IIS的各种身份验证详细测试
查看>>
JavaScript特效源码(3、菜单特效)
查看>>
聊聊、Zookeeper Linux 单服务
查看>>
Linux常用命令总结
查看>>
KRPano动态热点专用素材图50多个,加动态热点使用方法
查看>>
yii模型ar中备忘
查看>>
C#线程入门
查看>>
CSS清除浮动方法
查看>>