设计一个函数,可以打印出一个数字的特定数字部分。

huangapple go评论60阅读模式
英文:

How to design a function that prints out specific digits of a number

问题

示例:

输入:

140

输出:

1 4 0

我想让它除以100,这样结果将是1,然后除以10,结果将是4,然后除以1,答案将是0。但我不确定如何实现它。我还想在方法中使用递归。

英文:

Example:

Input:

140

Output:

1 4 0

I wanted to make it divide by 100 so that the outcome will be 1, and then divide by 10 and the outcome will be 4 and then by 1 and the answer will be 0. But I am not sure how I am able to achieve it. I also want to use recursion in the method.

答案1

得分: 1

你可以将整数视为字符串。

int n = 140;
String s = String.valueOf(n);
for (int i = 0; i < s.length(); i++) {
    System.out.println(s.charAt(i));
}

无需使用递归。

使用递归,可以像这样(我没有尝试过,所以可能不起作用):

public String separateInteger(int n) {
    if (n < 10) {
        return String.valueOf(n);
    } else {
        int mod = n % 10;
        int quot = n / 10;
        return String.valueOf(mod) + separateInteger(quot);
    }
}

希望已经回答了你的问题。 设计一个函数,可以打印出一个数字的特定数字部分。

英文:

You can see an int as a String

int n = 140;
String s = String.valueOf(n);
for(int i = 0; i&lt;s.length(); i++){
    System.out.println(s.charAt(i));
}

With no need of recursion.

With recursion it could be something like (i haven't tried it so it could not work):

public String separateInteger(int n){
   if(n &lt; 10){
       return String.valueOf(n);
   }
   else{ 
       int mod = n%10;
       int quot = n/10;
       return String.valueOf(mod) + separateInteger(quot);
   }
}

I hope have answered your question. 设计一个函数,可以打印出一个数字的特定数字部分。

huangapple
  • 本文由 发表于 2020年8月12日 00:27:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/63362444.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定