资讯专栏INFORMATION COLUMN

[LintCode/LeetCode] Integer Replacement

fyber / 2750人阅读

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 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
Solution
public class Solution {
    /**
     * @param n: a positive integer 
     * @return: the minimum number of replacements
     */
    public int integerReplacement(int n) {
        // Write your code here
        if (n == 1) return 0;
        if (n == Integer.MAX_VALUE) return 32;
        int count = 0;
        while (n > 1) {
            if (n % 2 == 0) {
                n /= 2;
                count++;
            } else {
                if ((n+1) % 4 == 0 && n != 3) {
                    n++;
                    count++;
                } else {
                    n--;
                    count++;
                }
            }
        }
        return count;
    }
}

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

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

相关文章

  • [LintCode/LeetCode] Edit Distance

    摘要:构造数组,是的,是的,是将位的转换成位的需要的步数。初始化和为到它们各自的距离,然后两次循环和即可。 Problem Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 s...

    snowell 评论0 收藏0
  • [LintCode/LeetCode] Decode Ways [String to Integer

    摘要:用将子字符串转化为,参见和的区别然后用动规方法表示字符串的前位到包含方法的个数。最后返回对应字符串末位的动规结果。 Problem A message containing letters from A-Z is being encoded to numbers using the following mapping: A -> 1 B -> 2 ... Z -> 26 Given ...

    andong777 评论0 收藏0
  • [LintCode/LeetCode] Find Median From / Data Stream

    摘要:建立两个堆,一个堆就是本身,也就是一个最小堆另一个要写一个,使之成为一个最大堆。我们把遍历过的数组元素对半分到两个堆里,更大的数放在最小堆,较小的数放在最大堆。同时,确保最大堆的比最小堆大,才能从最大堆的顶端返回。 Problem Numbers keep coming, return the median of numbers at every time a new number a...

    zxhaaa 评论0 收藏0
  • [LintCode/LeetCode] Flatten Nested List Iterator

    摘要:首先,根据迭代器需要不断返回下一个元素,确定用堆栈来做。堆栈初始化数据结构,要先从后向前向堆栈压入中的元素。在调用之前,先要用判断下一个是还是,并进行的操作对要展开并顺序压入对直接返回。 Problem Given a nested list of integers, implement an iterator to flatten it. Each element is either...

    spacewander 评论0 收藏0
  • [LintCode/LeetCode] Min Stack/Max Stack

    Problem Implement a stack with min() function, which will return the smallest number in the stack. It should support push, pop and min operation all in O(1) cost. Example push(1)pop() // return 1pus...

    GHOST_349178 评论0 收藏0

发表评论

0条评论

fyber

|高级讲师

TA的文章

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