zoukankan      html  css  js  c++  java
  • Binary System

    Description

    Usually we use number in the decimal system, for it is so convenient for us to remember and calculate.
    But it is not the same in the computer world where numbers are always stored in the binary system. For example, the number 21 in decimal can be presented as (21)10 = (10101)2 = 24+22+20. It is the sum of the power of 2. Note that in the first item, the power is 4, then the number 4 can be presented as (4)10 = (100)2=22, so , and it is much more convenient for computer to display as 21=2(2(2))+2(2)+2(0). Every positive integer can be written in this form following these principles: 
    1. Number 1 is presented as 2(0), while number 2 is presented as 2. Then other numbers must be combined by these two basic numbers;
    2. The powers of 2 are always sorted in descending order .

     

    Input

    Each line of the Input is the number n (0 < n < 1000000) in the binary system. Input file is ended with -1.

    Output

    For each case, you should only export the equation as the sample output. Be careful of the space before and after the equal sign. And there mustn’t be any more space in your output.

    Sample Input

    8
    21
    1315
    -1

    Sample Output

    8 = 2(2+2(0))
    21 = 2(2(2))+2(2)+2(0)
    1315 = 2(2(2+2(0))+2)+2(2(2+2(0)))+2(2(2)+2(0))+2+2(0)
    
    题意:把一个十进制的数转化成以2为底的若干个整数和。

    思路:递归。n=2(a)+2(b)+...+2(x)。而a,b,...,x分别又是相当于n。注意边界。


    #include<stdio.h>
    void work(int n)
    {
        int a[30],i=0;
        while(n>0) {
            a[i++]=n%2;
            n/=2;
        }
        for(int j=i-1;j>=0;j--)
            if(a[j])  {
                if(j<i-1) printf("+");
                if(j!=1 && j!=0) {
                    printf("2(");
                    work(j);
                    printf(")");
                }
                else if(j==1) printf("2");
                else printf("2(0)");
            }
    }
    int main()
    {
        int n;
        while(~scanf("%d",&n) && n!=-1) {
            printf("%d = ",n);
            work(n);
            printf("
    ");
        }
        return 0;
    }
    


    版权声明:本文博客原创文章。博客,未经同意,不得转载。

  • 相关阅读:
    ORA-00603 ORA-27504 ORA-27300 ORA-27301 ORA-27302
    ORA-03137: TTC protocol internal error : [12333] [7] [9] [50] [] [] [] []
    adg 搭建备库,归档缺失(GAP)
    redis 脚本扫描
    Oracle 查询历史连接主机信息
    11G RAC 参数文件损坏
    oracle 监控索引的使用状况
    11G ORA-07445 [evaopn3()+135]
    java共享锁实现原理及CountDownLatch解析
    轻松学习java可重入锁(ReentrantLock)的实现原理
  • 原文地址:https://www.cnblogs.com/lcchuguo/p/4752158.html
Copyright © 2011-2022 走看看