397. Integer Replacement

来源:互联网 发布:外星人设置灯光软件 编辑:程序博客网 时间:2024/06/08 21:49

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


分析如下:

https://discuss.leetcode.com/topic/58334/a-couple-of-java-solutions-with-explanations

结论:1.如果n是偶数 折半

2 如果n=3或者n-1中的1的位数比n+1中1的位数少那么n-1

3其余情况n+1

补充java方法: Integer.bitCount(int n)   返回n(二进制)中1的位数

>> 右移一位  <<左移一位 >>>忽略符号位右移一位, 用0补齐 此处需用这个! 否则会溢出2147483647


public int integerReplacement(int n) {    int c = 0;    while (n != 1) {        if ((n & 1) == 0) {            n >>>= 1;      //这个地方要用n>>>1  如果用n=n/2 出现溢出问题   需要考虑?        } else if (n == 3 || Integer.bitCount(n + 1) > Integer.bitCount(n - 1)) {            --n;        } else {            ++n;        }        ++c;    }    return c;}

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) {     //留意后两位 奇数是最后一位是1 如果倒数第二位是0那么减1 使得1的位数更少            --n;        } else {            ++n;        }        ++c;    }    return c;}




0 0