java 解释下代码

来源:百度知道 编辑:UC知道 时间:2024/06/28 13:34:00
用递归

public static void main(String args[]) {
// 使用时传入要计算的数 和 1 就可以了
System.out.println(sum(3,1));
}

/**
* 递归计算
* @param a 所要计算的数 a
* @param count 表示当前是几位数,每次递归+1
* @return
*/
public static int sum(int a,int count) {
String temp = "" ;
for (int i = 0;i < count;i++) {
temp += a ;
}
if (count < a) {
return Integer.parseInt(temp) + sum(a,count+1);//""转成int 是什么
} else if (count == a) {
return Integer.parseInt(temp);
} else {
return 0 ;
}
}

第一个回答是对的。以输入为3,1为例:
首次调用sum(3,1)
count=1
for (int i = 0;i < count;i++) {
temp += a ;
}
i取0 temp=3

因为count<a (因为a=3)
则调用sum(3,2)
count=2
for (int i = 0;i < count;i++) {
temp += a ;
}
i取0, temp=3
i取1 temp=33

因为count<a (因为a=3)
则调用sum(3,3)
count=3
for (int i = 0;i < count;i++) {
temp += a ;
}
i取0, temp=3
i取1 temp=33
i取2 temp=333

然后求和3+33+333
这里面涉及到了字符串和整数之间的转换。
temp += a ;即把字符串temp末尾加上a(这里面会自动把整数型的数据a转换为字符串)
Integer.parseInt(temp) ;即将字符创temp转换为整数型。

以此类推。输入2,1
结果为2+22=24;
输入3,1
结果为3+33+333;
输入4,1
结果为4+44+444+4444;
输入3,2
结果为3+33
不知道我说的是否清楚

递归的塔形计算,比如你传入3,1就是
3+33+333
4,2的话就是
44+444+4444

temp += a ;
有错误吧。。

这段代码你想知道什么?

转成int就变成3、33、333
我这有一个调试的程序,你看看就明白了
public static void main(St