资讯专栏INFORMATION COLUMN

[LeetCode] Integer Replacement

XFLY / 1792人阅读

摘要:记一种简单的的做法先讨论边界,若为最大值,返回然后对整数分奇偶两种情况讨论,偶数除以,奇数判断是否后能被整除且不等于,若如此则,否则每次操作后计数器,循环结束后返回计数器值。

Problem

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

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

Note

记一种简单的iteration的做法:
先讨论边界case,若n为Integer最大值,返回32.
然后对整数n分奇偶两种情况讨论,偶数除以2,奇数判断是否+1后能被4整除且n不等于3,若如此则+1,否则-1. 每次操作后计数器+1,循环结束后返回计数器值。

Solution
public class Solution {
    public int integerReplacement(int n) {
        if (n == Integer.MAX_VALUE) return 32;
        int count = 0;
        while (n != 1) {
            if (n%2 == 0) n/=2;
            else {
                if ((n+1)%4==0 && n!=3) n+=1;
                else n-=1;
            }
            count++;
        }
        return count;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/66036.html

相关文章

  • LeetCode[397] Integer Replacement

    摘要:复杂度思路利用位的操作。如果一个数是奇数,那么末位的位一定是。对于偶数,操作是直接除以。对于奇数的操作如果倒数第二位是,那么的操作比的操作能消掉更多的。还有一个的地方是,为了防止越界,可以将先转换成。 LeetCode[397] Integer Replacement Given a positive integer n and you can do operations as fo...

    Drinkey 评论0 收藏0
  • [LintCode/LeetCode] Integer Replacement

    Problem 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 re...

    fyber 评论0 收藏0
  • leetcode397. Integer Replacement

    摘要:题目要求思路和代码可以发现除二后所得到的结果一定优于加减。因此,如果当前奇数除二为偶数,则直接做除法,否则将当前奇数加一再除以二,得到偶数的结果。 题目要求 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...

    quietin 评论0 收藏0
  • Leetcode 397. Integer Replacement

    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 ...

    sutaking 评论0 收藏0
  • [轮子系列]Google Guava之CharMatcher源码分析

    摘要:子类通过实现方法或重写其他父类的方法,从而提供了各种不同的具体操作,如判断是否为某一个字符,判断是否为数字字符,判断是否为字符等。 showImg(https://segmentfault.com/img/bVbe1IW?w=300&h=300); 本文源地址:http://www.fullstackyang.com/...,转发请注明该地址或segmentfault地址,谢谢! 最近...

    pekonchan 评论0 收藏0

发表评论

0条评论

XFLY

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<