猿问

Java - 扩展形式的数字

我已经给出了数字并希望它以扩展形式作为字符串返回。例如


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;

}

我认为第二个循环有问题,但不知道为什么。


慕容708150
浏览 223回答 3
3回答

FFIVE

您应该将 '0' 添加到str[i],而不是str[j]:&nbsp; for(int i = 0; i < str.length-1; i++) {&nbsp; &nbsp; if(Integer.valueOf(str[i]) > 0) {&nbsp; &nbsp; &nbsp; for(int j = i; j < str.length-1; j++) {&nbsp; &nbsp; &nbsp; &nbsp; str[i] += '0';&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; }这将导致:70000 + 0 + 300 + 0 + 4您仍然必须摆脱 0 位数字。摆脱它们的一种可能方法:result = result.substring(1, result.length()-1).replace(", 0","").replace(",", " +");现在输出是70000 + 300 + 4

ibeautiful

伪代码使用整数算法来一一提取十进制数字(从右边开始):mul = 1&nbsp; &nbsp; //will contain power of 10while (num > 0):&nbsp; &nbsp; &nbsp;dig = num % 10&nbsp; &nbsp; //integer modulo retrieves the last digit&nbsp; &nbsp; &nbsp;if (dig > 0):&nbsp; &nbsp;//filter out zero summands&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; add (dig * mul) to output&nbsp; &nbsp;//like 3 * 100 = 300&nbsp; &nbsp; &nbsp;num = num / 10 //integer division removes the last decimal digit&nbsp; 6519 => 651&nbsp; &nbsp; &nbsp;mul = mul * 10&nbsp; &nbsp; //updates power of 10 for the next digit

慕虎7371278

你可以用纯数学做同样的事情,使用 modulo%和 integer Division /,例如使用StreamAPI:int n = 70304;String res = IntStream&nbsp; &nbsp; &nbsp; &nbsp; .iterate(1, k -> n / k > 0, k -> k * 10) // divisors&nbsp; &nbsp; &nbsp; &nbsp; .map(k -> (n % (k*10) / k ) * k)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// get 1s, 10s, 100s, etc.&nbsp; &nbsp; &nbsp; &nbsp; .filter(x -> x > 0)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // throw out zeros&nbsp; &nbsp; &nbsp; &nbsp; .mapToObj(Integer::toString)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// convert to string&nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.joining(" + "));&nbsp; &nbsp; &nbsp;// join with '+'System.out.println(res); // 4 + 300 + 70000
随时随地看视频慕课网APP

相关分类

Java
我要回答