アルゴリズムメモ_01:ブルーブリッジカップ練習2の次べき乗表示(Java)

2206 ワード



   2 , :137 2 10001001。
   2 2 , , :137=27+23+2^0
   , a^b a(b)
   ,137 :2(7)+2(3)+2(0)
   :7=22+2+20 (2^1 2 )
  3=2+2^0
   137 :2(2(2)+2+2(0))+2(2+2(0))+2(0)
   :1315=210+28+2^5+2+1
   1315 :
  2(2(2+2(0))+2)+2(2(2+2(0)))+2(2(2)+2(0))+2+2(0)

   (1<=n<=20000)

   n 0,2 ( )



137

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

1315

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

  

import java.util.ArrayList;
import java.util.Scanner;

//eg: 11 = 2^3+2^1+2^0

public class      {
    public ArrayList get10To2(int n) {
        ArrayList list = new ArrayList(); // ArrayList.add()       
                                                            
        int count = 0;
        while (n != 0) {
            int temp = n % 2;
            if (temp == 1)
                list.add(count); //       “1”   ,       “3”、“1”、“0”;
            n = n >> 1;
            count++;
        }
        return list;
    }

    public void printResult(int n) {
        if (n == 0) //     n=0;  0
            System.out.print("0");
        ArrayList list = get10To2(n);
        for (int i = list.size() - 1; i >= 0; i--) {
            System.out.print("2"); //
            if (list.get(i) != 1) { //    1、0 ,    
                System.out.print("(");
                printResult(list.get(i));
                System.out.print(")");
            }
            if (i != 0) { // list       ,    2     “+”
                System.out.print("+");
            }
        }
    }

    public static void main(String[] args) {
             test = new     ();
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        test.printResult(n);
    }

}