蓝桥杯 试题 算法训练 幂方分解

资源限制
时间限制: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;
//20000的二进制为100111000100000 15位
public class Main2 {
public static void main(String[] args) {
  Scanner scan=new Scanner(System.in);
  int n=scan.nextInt();
  int count=0;
  String s=Integer.toBinaryString(n);
  String res="";
  for (int i =s.length()-1; i>=0; i--) {
     if(s.charAt(i)=='1') {
    	if(count<4) {
    	   if(res=="") {
    		   res=fun(count);		
    	   }else{
    		   res=fun(count)+"+"+res;	  
    	   }
    	}else if(count<8) {
    	   res="2("+fun(2)+fun1(count-4)+")"+"+"+res;	
    	}else if(count<12){
    	   res="2("+fun(3)+fun1(count-8)+")"+"+"+res;		
    	}else { //count最大值为14,没必要细分
    	   res="2("+fun(3)+"+"+fun(2)+fun1(count-12)+")"+"+"+res;
    	}
    	 count++;
     }else {
    	 count++; 
    	 continue;  
     }
 }
 System.out.println(res);
}

private static String fun1(int i) {
	String res="";
	if(i==4) {
		return "+"+fun(2);
	}
	if(i==3) {
		return "+"+fun(1)+"+"+fun(0);  
	}
	if(i==2) {
		return "+"+fun(1); 
	}
	if(i==1) {    
		return "+"+fun(0);
	}else {
    	return "";
    }
}

public static String fun(int count) {
	String res="";
	if(count==3) {
		res="2(2+2(0))";   // 2的三次方 :8
	}
	if(count==2) {
		res="2(2)"; //2的二次方:4
	}
	if(count==1) {     //2的一次方:2
		res="2";
	}
	if(count==0) {     //2的零次方:1
		res="2(0)";
	}
	return res;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CZDXWX

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值