为了账号安全,请及时绑定邮箱和手机立即绑定

Java - 扩展形式的数字

Java - 扩展形式的数字

慕容708150 2021-09-03 12:31:36
我已经给出了数字并希望它以扩展形式作为字符串返回。例如expandedForm(12); # Should return "10 + 2"expandedForm(42); # Should return "40 + 2"expandedForm(70304); # Should return "70000 + 300 + 4"我的函数适用于第一种和第二种情况,但使用 70304 它给出了这个:70 + 00 + 300 + 000 + 4这是我的代码import java.util.Arrays;public static String expandedForm(int num){  String[] str = Integer.toString(num).split("");  String result = "";  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[j] += '0';      }    }  }  result = Arrays.toString(str);  result = result.substring(1, result.length()-1).replace(",", " +");  System.out.println(result);  return result;}我认为第二个循环有问题,但不知道为什么。
查看完整描述

3 回答

?
FFIVE

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


查看完整回答
反对 回复 2021-09-03
?
ibeautiful

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


查看完整回答
反对 回复 2021-09-03
?
慕虎7371278

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


查看完整回答
反对 回复 2021-09-03
  • 3 回答
  • 0 关注
  • 219 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信