日期:2014-05-18  浏览次数:20893 次

50分求一算法
有一个值,如127,
127=1+2+4+8+16+32+64 //后面的一个数等于前面数*2
5=1+4 //中间的2有可能断层,复选框未选中
我怎样才能算出这个数是有哪些这样的数字相加的,1,2,4,8,16,32,64或1,4

------解决方案--------------------
转成2进制就很容易了!
------解决方案--------------------
public static void main(String[] args) {
//System.out.println(sum(100));

int a = 10;
String print;
int b=a;
int count = 0;
int time = 0;
int i = -1;
int[] times = new int[100];
while (a > 1) {
if (a % 2 > 0) {
count += 2 >> time;
a++;
times[++i] = time;
}

a = a / 2;
time++;
}
i = 1;
if (count == 0)
print = a + "=" + a;
else {
if (b % 2 > 0) {
print =b+ "=1";
for (int j = 0; j < time; j++)
if (j != times[i])
print += "+" + (2 << (j-1));
else if (i < times.length - 2)
i++;
print = print.replaceAll("0\\+","");
} else {
i = 1;
print = b+"=";
for (int k = 1; k < time; k++)
if (k != times[i]) {
System.out.println(k);
print += "+" + (2 << (k-1));
} else if (i < times.length - 2) {
i++;
}
print = print.replaceFirst("\\+","");
}
}

System.out.println(print);

}