ALGO-12 幂方分解

ALGO-12 幂方分解

题目

资源限制

时间限制:1.0s 内存限制:256.0MB

问题描述

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

例如:
\(137=2^7+2^3+2^0\)
同时约定方次用括号来表示,即 ab 可表示为 a(b)。
由此可知,137 可表示为:
2(7)+2(3)+2(0)

进一步:
\(7= 2^2+2+2^0\) (21 用 2 表示)
\(3=2+2^0\)

所以最后 137 可表示为:
2(2(2)+2+2(0))+2(2+2(0))+2(0)

又如:
\(1315=2^{10} +2^8 +2^5 +2+1\)
所以 1315 最后可表示为:
2(2(2+2(0))+2)+2(2(2+2(0)))+2(2(2)+2(0))+2+2(0)

输入格式

输入包含一个正整数 N(N<=20000),为要求分解的整数。

输出格式

程序输出包含一行字符串,为符合约定的 n 的 0,2 表示(在表示中不能有空格)

题解

import java.util.Scanner;

public class ALGO_12 {
    // NOTE: powers is the different power of 2 (less than 20,000), for the function----divide
    static int[] powers = { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384 };
    // NOTE: buffer is a container to store the results
    static StringBuffer buffer = new StringBuffer();

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        sc.close();
        divide(n);
        // fun(n);
        System.out.println(buffer);
    }

    /**
     * @description divide any positive integer into a power of 2
     * @param {Integer} n
     * @return a String of the result of division
     */
    static void divide(int n) {
        // NOTE: three exports
        if (n == 0)
            return;//注意这结束标志
        if (n == 1) {
            buffer.append("2(0)");
            return;
        }
        if (n == 2) {
            buffer.append("2");
            return;
        }
        // NOTE: start with the highest sign
        int sign = powers.length - 1;
        while (powers[sign] > n && sign >= 0)
            sign--;//找到最接近n的幂指数
        buffer.append("2");
        if (sign > 1)//注意2并不用分解,不是用2(2(0))表示.
        {
            buffer.append("(");
            divide(sign);
            buffer.append(")");
        }
        // NOTE: next digit
        n -= powers[sign];
        if (n != 0)
            buffer.append("+");
        divide(n);
    }

    /**
     * @description divide any positive integer into a power of 2
     * @param {Integer} n
     * @return a String of the result of division
     */
    static void fun(int n) {
        int co = 0;
        // NOTE: because of n<20,000, the sign is 31
        for (int sign = 31; sign >= 0; sign--) {
            // NOTE: `(1<<sign & n)!=0` filter each digit from the binary of n, because of the binary of n is the primary division of n
            if ((1 << sign & n) != 0) {
                if (co++ != 0)
                    buffer.append("+");
                if (sign == 0) {
                    buffer.append("2(0)");
                } else if (sign == 1) {
                    buffer.append("2");
                } else {
                    buffer.append("2(");
                    fun(sign);
                    buffer.append(")");
                }
            }
        }
    }
}

posted @ 2022-03-18 16:16  morning-start  阅读(37)  评论(0编辑  收藏  举报