蓝桥杯 [ALGO-12] 幂方分解

算法训练 幂方分解

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

问题描述

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

137=27+23+20 

同时约定方次用括号来表示,即ab 可表示为a(b)。

由此可知,137可表示为:

2(7)+2(3)+2(0)

进一步:7= 22+2+20 (21用2表示)

3=2+20 

所以最后137可表示为:

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

又如:

1315=210 +28 +25 +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 Main {

    private static int[] nums = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384};

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            int n = scanner.nextInt();
            showResult(n, 14);
            System.out.println();
        }
    }

    /**
     * @param n     数值
     * @param index nums数组的下标
     */
    private static void showResult(int n, int index) {
        if (index == 0) {
            System.out.print("0");
            return;
        }
        if (index == 1) {
            System.out.print("2(0)");
            return;
        }
        while (index >= 0) {
            if (n - nums[index] >= 0) {
                if (index != 1) {
                    System.out.print("2(");
                    showResult(index, index);
                    System.out.print(")");
                } else System.out.print("2");
                n -= nums[index];
                if (n != 0) {
                    System.out.print("+");
                    showResult(n, index);
                    return;
                }
            }
            index--;
        }
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值