0
点赞
收藏
分享

微信扫一扫

2的次幂表示


2的次幂表示  


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

问题描述



  任何一个正整数都可以用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)

提示
用递归实现会比较简单,可以一边递归一边输出
【程序】
用java语言编写程序,代码如下:

import java.io.BufferedInputStream;
import java.util.Scanner;

public class Power {
public static void main(String[] args) {
Scanner input = new Scanner(new BufferedInputStream(System.in));
int n = input.nextInt();
output(n);
}

public static void output(int n) {

if(n == 1) return;
if(n == 0) {
System.out.print("0");
return;
}

int[] base = new int[100];
int i = 0;
do {
base[i++] = n % 2;
n = n / 2;
} while(n != 0);

boolean first = true;
for(int j = i - 1; j >= 0; j--) {
if(base[j] == 1) {
if(first) {
System.out.print("2");
first = false;
}
else {
System.out.print("+2");
}
if(j != 1)
System.out.print("(");
output(j);
if(j != 1)
System.out.print(")");
}
}
}
}


举报

相关推荐

0 条评论