如何使用递归方法(无字符串)打印带逗号除数的 int?
How to print an int with comma divisors using a recursive method (no strings)?
在我的计算机科学 class 中,我们被分配了一个递归实验室,在该实验室中,我们必须打印出一个用逗号分隔 3 位数字组的数字。
这是直接来自作业的文本(该方法必须是递归的):
Write a method called printWithCommas that takes a single nonnegative
primitive int argument and displays it with commas inserted properly.
No use of String.
For example printWithCommas(12045670); Displays 12,045,670
printWithCommas(1); Displays 1
我真的被这个难住了。到目前为止,这是我的代码:
public static void printWithCommas(int num) {
//Find length
if (num < 0) return;
int length = 1;
if (num != 0) {
length = (int)(Math.log10(num)+1);
}
//Print out leading digits
int numOfDigits = 1;
if (length % 3 == 0) {
numOfDigits = 3;
}
else if ((length+1) % 3 == 0) {
numOfDigits = 2;
}
System.out.print(num / power(10,length-numOfDigits));
//Print out comma
if (length > 3) {
System.out.print(',');
}
printWithCommas(num % power(10,length-numOfDigits));
}
它出现堆栈溢出(我稍后可以修复),但它无法打印出一些零,特别是每个逗号之后应该出现的零。
我觉得我正在用一种完全错误的方法来处理这个问题,但想不出一个好的方法。任何帮助将不胜感激。
提前致谢!
注意:power
是我做的一个计算幂的函数。第一个参数是底数,第二个是指数。
这是我想出的代码,供其他可能卡在上面的人参考:
public static void printWithCommas(int num) {
if (num > 999) {
printWithCommas(num/1000);
System.out.print(',');
if (num % 1000 < 100) System.out.print('0');
if (num % 1000 < 10) System.out.print('0');
System.out.print(num%1000);
}
else {
System.out.print(num);
}
}
在我的计算机科学 class 中,我们被分配了一个递归实验室,在该实验室中,我们必须打印出一个用逗号分隔 3 位数字组的数字。 这是直接来自作业的文本(该方法必须是递归的):
Write a method called printWithCommas that takes a single nonnegative primitive int argument and displays it with commas inserted properly. No use of String.
For example printWithCommas(12045670); Displays 12,045,670
printWithCommas(1); Displays 1
我真的被这个难住了。到目前为止,这是我的代码:
public static void printWithCommas(int num) {
//Find length
if (num < 0) return;
int length = 1;
if (num != 0) {
length = (int)(Math.log10(num)+1);
}
//Print out leading digits
int numOfDigits = 1;
if (length % 3 == 0) {
numOfDigits = 3;
}
else if ((length+1) % 3 == 0) {
numOfDigits = 2;
}
System.out.print(num / power(10,length-numOfDigits));
//Print out comma
if (length > 3) {
System.out.print(',');
}
printWithCommas(num % power(10,length-numOfDigits));
}
它出现堆栈溢出(我稍后可以修复),但它无法打印出一些零,特别是每个逗号之后应该出现的零。
我觉得我正在用一种完全错误的方法来处理这个问题,但想不出一个好的方法。任何帮助将不胜感激。
提前致谢!
注意:power
是我做的一个计算幂的函数。第一个参数是底数,第二个是指数。
这是我想出的代码,供其他可能卡在上面的人参考:
public static void printWithCommas(int num) {
if (num > 999) {
printWithCommas(num/1000);
System.out.print(',');
if (num % 1000 < 100) System.out.print('0');
if (num % 1000 < 10) System.out.print('0');
System.out.print(num%1000);
}
else {
System.out.print(num);
}
}