Training algorithm represents the power of two
Resource constraints
Time limit: 1.0s Memory Limit: 512.0MB
Problem Description
Any positive integer may be represented in binary, for example: 137 is represented as 10001001 binary.
This represents a binary power of 2, written in the form and, so that the top surface of the high-power, gives the following expression: 137 = 2 7 + 2 3 + 2 ^ 0
Now agreed with powers of brackets He indicates that a ^ b is expressed as a (b)
In this case, 137 may be expressed as: 2 (7) + 2 (3) + 2 (0)
further: 7 = 2 2 + 2 + 2 0 (2 ^ 1 with 2 represents a)
3 + 2 ^ 2 = 0
so finally 137 can be expressed as: 2 (2 (2) + 2 + 2 (0)) 2 + (2 + 2 (0)) 2 + (0)
Another example: 1315 2 = 10 + 2 8 + 2 + 2 + 1 ^ 5
it can be expressed as the final 1315:
2 (2 (2 + 2 (0)) + 2) + 2 (2 (2 + 2 (0))) + 2 (2 (2) + 2 (0)) + 2 + 2 (0)
Input Format
Positive integer (1 <= n <= 20000)
Output Format
In line with the agreed n represents 0,2 (no spaces in the representation)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int n=in.nextInt();
System.out.println( toResult(n));
}
//转换为2进制
public static String toBin(int n){
return Integer.toBinaryString(n);
}
//第一步
public static String toResult(int n){
StringBuilder sb=new StringBuilder();
String str=toBin(n);
int len=str.length()-1;
for (char c:str.toCharArray()) {
if(c=='1'){
if(len==2)
sb.append("2("+len+")");
else if(len==1)
sb.append("2");
else
//递归输出
sb.append("2("+toResult(len)+")");
if(len!=0)
sb.append("+");
}
len--;
}
if(sb.toString().equals("")||sb.equals(null))
return "0";
if(sb.charAt(sb.length()-1)=='+')
sb.deleteCharAt(sb.length()-1);
return sb.toString();
}
}