zoukankan      html  css  js  c++  java
  • Vijos P1597 2的幂次方【进制+递归】

    描述

    任何一个正整数都可以用2的幂次方表示。

    同时约定用括号来表示方次,即a的b次,可以表示为a(b).
    由此可知,137可以表示为:
    2(7)+2(3)+2(0)
    进一步:
    7=2(2)+2+2(0)(2的1次用2表示)
    3=2+2(0)
    所以137可以表示为:
    2(2(2)+2+2(0))+2(2+2(0))+2(0)
    按2的次幂降次排列。

    格式

    输入格式

    正整数n(n<=20000)

    输出格式

    用0,2表示符合约定的n(在表格中不能有空格)。

    样例1

    样例输入1

    137
    

    样例输出1

    2(2(2)+2+2(0))+2(2+2(0))+2(0)
    

    限制

    1S

    来源

    NOIP 1998


    问题链接 Vijos P1597 2的幂次方

    问题分析

    这是一个进制转换问题,用递归程序实现是方便的。

    程序说明

    函数convert(int n, int e)实现n的e次方转换为其2的幂次方表示。

    这个程序是先前做的,直接拿过来用,参见参考链接。

    题记

    进制是常见的话题,递归程序到处可见。


    参考链接CCF NOI1074 2的幂次方表示


    AC的C程序如下:

    #include <stdio.h>  
      
    #define BASE 2  
      
    void convert(int n, int e)  
    {  
        int digit, quotient;  
      
        if(e == 0) {  
            if(n == 0)  
                ;  
            else if( n == 1)  
                printf("2(0)");  
            else if(n == 2)  
                printf("2");  
            else {  
                convert(n / BASE, e+1);  
                digit = n % BASE;  
                if(digit) {  
                    printf("+");  
                    convert(digit, e);  
                }  
            }  
        } else {  
            quotient = n / BASE;  
            digit = n % BASE;  
            if(quotient > 0) {  
                convert(quotient, e+1);  
                if(digit)  
                    printf("+");  
      
            }  
            if(digit) {  
                if(e == 1)  
                    printf("2");  
                else {  
                    printf("2(");  
                    convert(e, 0);  
                    printf(")");  
                }  
            }  
        }  
    }  
      
    int main(void)  
    {  
        int n;  
      
        scanf("%d", &n);  
      
        convert(n, 0);  
        printf("
    ");  
      
        return 0;  
    }  
      
    /* 
    12345 
    2(2(2+2(0))+2(2)+2(0))+2(2(2+2(0))+2(2))+2(2(2)+2(0))+2(2(2))+2(2+2(0))+2(0) 
    */ 







  • 相关阅读:
    Solr4.8.0源码分析(12)之Lucene的索引文件(5)
    JAVA基础(1)之hashCode()
    Solr4.8.0源码分析(11)之Lucene的索引文件(4)
    检查数据不一致脚本
    索引的新理解
    数据库放到容器里
    动态规划
    每天晚上一个动态规划
    postgresql parallel join example
    名不正,则言不顺
  • 原文地址:https://www.cnblogs.com/tigerisland/p/7563790.html
Copyright © 2011-2022 走看看