英文:
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<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 < 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论