3 回答
TA贡献1797条经验 获得超6个赞
您应该将 '0' 添加到str[i],而不是str[j]:
for(int i = 0; i < str.length-1; i++) {
if(Integer.valueOf(str[i]) > 0) {
for(int j = i; j < str.length-1; j++) {
str[i] += '0';
}
}
}
这将导致:
70000 + 0 + 300 + 0 + 4
您仍然必须摆脱 0 位数字。
摆脱它们的一种可能方法:
result = result.substring(1, result.length()-1).replace(", 0","").replace(",", " +");
现在输出是
70000 + 300 + 4
TA贡献1993条经验 获得超5个赞
伪代码使用整数算法来一一提取十进制数字(从右边开始):
mul = 1 //will contain power of 10
while (num > 0):
dig = num % 10 //integer modulo retrieves the last digit
if (dig > 0): //filter out zero summands
add (dig * mul) to output //like 3 * 100 = 300
num = num / 10 //integer division removes the last decimal digit 6519 => 651
mul = mul * 10 //updates power of 10 for the next digit
TA贡献1802条经验 获得超4个赞
你可以用纯数学做同样的事情,使用 modulo%和 integer Division /,例如使用StreamAPI:
int n = 70304;
String res = IntStream
.iterate(1, k -> n / k > 0, k -> k * 10) // divisors
.map(k -> (n % (k*10) / k ) * k) // get 1s, 10s, 100s, etc.
.filter(x -> x > 0) // throw out zeros
.mapToObj(Integer::toString) // convert to string
.collect(Collectors.joining(" + ")); // join with '+'
System.out.println(res); // 4 + 300 + 70000
添加回答
举报