题意:给一个数,求其幂次方表示,比如:
可以表示为
输出答案必须只包含2和0,故137应该输出:
思路:分治,字符串操作还是Java方便
import java.util.Scanner;
public class Main {
public String solve(int n) {
String res = "";
int x = 1;
if (n == 0)
return res;
while (Math.pow(2, x) < n) {
x++;
}
if (Math.pow(2, x) > n)
x--;
if (x > 2) {
res += "2(";
res += solve(x);
res += ")+";
}
else {
if (x == 1)
res += "2+";
else {
res += "2(" + x + ")+";
}
}
int k = (int) Math.pow(2, x);
res += solve(n%k);
if (res.charAt(res.length()-1) == '+')
res = res.substring(0, res.length()-1);
return res;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextInt()) {
int n = in.nextInt();
System.out.println(new Main().solve(n));
}
}
}