Integer_Replacement

来源:互联网 发布:供应链管理公司云计算 编辑:程序博客网 时间:2024/06/15 01:32

题目描述:

    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?
    (给定一个正整数n,您可以按照如下方式执行操作:
      如果n是偶数,用n/2替换n。
      如果n是奇数,则可以用n + 1或n - 1替换n。
     n成为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

思路:本题说用最少替换数,那么最少的替换数意味着出现奇数 的次数越少越好,偶数就可以直接除2,而不是还要进行替换。
         题目中说到奇数n可以用n+1或n-1替换,而究竟使用n+1还是n-1是本题的关键。一个数变为二进制之后,在进行除2
        (实际上就是进行向右移位操作>>)操作之后究竟是偶数还是奇数要看的是其二进制从左往右的倒数第二位,例如7转化
         为二进制之后(0111)除2,变为3(0011),而5(0101)除2,变为2(0010),那么从上面这两个例子来看一个
         数转化为二进制表达后,1的数量越少,后面除二变为奇数的次数越少。而在题目中要对奇数n进行+1或-1,两种处理中
         能使n的二进制中的1更少的处理即为我们要选择的处理。
         奇数又分为以11结尾的和以01结尾的:
         1.以01结尾的奇数:
            9(1001) + 1 = 10(1010)
            9(1001) - 1 = 8(1000)
         明显可以看出以01结尾的奇数-1会比+1产生1更少的数。
         2.以11结尾的奇数
           15(1111)+ 1 = 16(10000)
           15(1111)- 1 = 14(1110)、
           明显可以看出以11结尾的奇数+1会比-1产生1更少的数。
    PS:在第一次进行提交之后,会在n=3时报错,发现3跟别的以11结尾的数不一样,他要-1才会得到更少的次数,是个特例。

public class Integer_Replacement {public static int integerReplacement(int n) {long num = n;        int count = 0;        while(num!=1)        {        if(num%2==0)        {        num >>= 1;        }        else        {        if(num==3)        num = num-1;        else        num = (num&2)==2 ? num+1 : num-1;        }        count++;        }        return count;    }public static void main(String[] args) {int n = 3;System.out.println(integerReplacement(n));}}


原创粉丝点击