九度 Online Judge 算法 刷题 题目1095:2的幂次方

时间:2023-02-12 12:44:39

题目1095:2的幂次方

题目描述:
Every positive number can be presented by the exponential form.For example, 137 = 2^7 + 2^3 + 2^0。
Let’s present a^b by the form a(b).Then 137 is presented by 2(7)+2(3)+2(0). Since 7 = 2^2 + 2 + 2^0 and 3 = 2 + 2^0 , 137 is finally presented by 2(2(2)+2 +2(0))+2(2+2(0))+2(0).

Given a positive number n,your task is to present n with the exponential form which only contains the digits 0 and 2.

输入:
For each case, the input file contains a positive integer n (n<=20000).
输出:
For each case, you should output the exponential form of n an a single line.Note that,there should not be any additional white spaces in the line.
样例输入:
1315
样例输出:
2(2(2+2(0))+2)+2(2(2+2(0)))+2(2(2)+2(0))+2+2(0)
来源:
2006年上海交通大学计算机研究生机试真题

code

java实现

import java.util.*;
public class Main {
    public static void main(String args[]) {
        Scanner cin = new Scanner(System.in);
        int a;
        while (cin.hasNext()) {
            a = cin.nextInt();
            StringBuilder buffer = new StringBuilder();
            String aString = Integer.toBinaryString(a);
            for(int i = 0; i < aString.length(); i++) {
                if(aString.charAt(i) == '1') {
                    int num = aString.length()-i-1;
                    if(num == 1)
                        buffer.append("2+");
                    else
                    buffer.append("2(" + changeAllNum(num) + ")+");
                }
            }
            String result = buffer.subSequence(0, buffer.length()-1).toString();
            System.out.println(result);
        }
    }
    public static String changeAllNum (int i ) {
        if(i<=7)
            return changeNum(i);
        else {
            StringBuilder buff  = new StringBuilder("2(2+2(0))");
            if(i == 9)
                buff.append("+2(0)");
            if(i>9)
                buff.append("+"+changeAllNum(i-8));
            return buff.toString();
        }
         
    }
    public static String changeNum (int i ) {
        switch (i){
            case 7:return "2(2)+2+2(0)";
            case 6:return "2(2)+2";
            case 5:return "2(2)+2(0)";
            case 4:return "2(2)";
            case 3:return "2+2(0)";
            case 2:return "2";
            case 1:return "";
            case 0:return "0";
        }
        return "";
    }
}
/**************************************************************
    Problem: 1095
    User: langzimaizan
    Language: Java
    Result: Accepted
    Time:80 ms
    Memory:15476 kb
****************************************************************/