Leetcode-397. Integer Replacement

来源:互联网 发布:深圳市软件行业协会 编辑:程序博客网 时间:2024/06/05 14:37

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。这次比赛略无语,没想到前3题都可以用暴力解。

博客链接:mcf171的博客

——————————————————————————————

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
这个题目我本来想着用dp做,但是没想到超时了。看了下discuss的说法,还是要位操作。Your runtime beats 55.55% of java submissions.

public 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;}}




0 0
原创粉丝点击