蓝桥杯练习系统算法训练 2的次幂表示

问题描述
  任何一个正整数都可以用2进制表示,例如:137的2进制表示为10001001。
  将这种2进制表示写成2的次幂的和的形式,令次幂高的排在前面,可得到如下表达式:137=2^7+2^3+2^0
  现在约定幂次用括号来表示,即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)
  又如: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)
输入格式
  正整数(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)

提示
用递归实现会比较简单,可以一边递归一边输出
package 算法训练;

import java.util.Scanner;

public class _2的次幂表示 {

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

	private static String   f(int n) {
		// TODO Auto-generated method stub
		int sum = 0;
		String result = "";
		for (int i = 15; i >= 0; i--) {
			int temp = (int) Math.pow(2, i);
			if (sum + temp < n) {
				String tempstr;
				sum += temp;
				if (i == 0) {
					tempstr = "2(0)";
				} else if (i == 1) {
					tempstr = "2";
				} else if (i == 2) {
					tempstr = "2(2)";
				} else {
					tempstr = "2(" + f(i) + ")";
				}
				result += (tempstr+"+");
			}
			if (sum + temp == n) {
				sum += temp;
				String tempstr;
				if (i == 0) {
					tempstr = "2(0)";
				} else if (i == 1) {
					tempstr = "2";
				} else if (i == 2) {
					tempstr = "2(2)";
				} else {
					tempstr = "2(" + f(i) + ")";
				}
				result += (tempstr);
				break;
			}
		}
	return result;
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值