[位运算]397. Integer Replacement

题目:397. Integer Replacement[Medium]

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

If n is even, replace n with n/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:
8
Output:
3
Explanation:
8 -> 4 -> 2 -> 1
Example 2:
Input:
7
Output:
4
Explanation:
7 -> 8 -> 4 -> 2 -> 1
or
7 -> 6 -> 3 -> 2 -> 1

想到了要用位运算,但是有几个要注意的点:

  1. 每个地方都要位运算防止超时‘
  2. 不要n++ 要 ++n
  3. +1和-1效果不一定相同,比如3(11)的-1效果更好
  4. 位运算每一步都要加括号
    [Runtime: 4 ms]
class Solution {
    public int integerReplacement(int n) {
        int count = 0;
        while(n>1){
             if((n & 1) == 1){
                 ++count;
                 if(n==3 || ((((n-1) >>>1) & 1) == 0)) --n;
                 else ++n;
             }
             n = n >>> 1;
             ++count;
        }
       return count;
        
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,779评论 0 33
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,026评论 19 139
  • 昨天晚上去佳旺吃饭,点餐给钱领了餐牌,找了位置就把牌子放在桌子上,然后就走了,去买喝的(快餐店的水太贵了)。 回来...
    入兴贵贤阅读 486评论 0 1
  • 若得夕阳无限好,何须惆怅近黄昏。 人生几回思往事,一片伤心画不成。
    慕容兰馨阅读 224评论 0 3
  • 步骤:1、空白分区。留给linux2、禁用快速启动 电源选项>电源按钮的功能>更改当前不可用的设置>取消快速启动...
    七宝qb阅读 466评论 0 0