我去面试,让我写一个N!的类。一个用递归,一个不用递归。
用递归的我写了出来了。不足的敬请指教。不用递归的想不出个合适的方法。请大虾们回一个。
public class FactorialDemo {
public static void main(String[] args) {
System.out.println(String.valueOf(factorial(4)));
}
static int factorial(int n) {
int temp = 0;
if (n == 0 || n == 1) {
temp = 1;
}else if (n > 1) {
temp = n * factorial(n - 1);
}
return temp;
}
}
用递归的我写了出来了。不足的敬请指教。不用递归的想不出个合适的方法。请大虾们回一个。
public class FactorialDemo {
public static void main(String[] args) {
System.out.println(String.valueOf(factorial(4)));
}
static int factorial(int n) {
int temp = 0;
if (n == 0 || n == 1) {
temp = 1;
}else if (n > 1) {
temp = n * factorial(n - 1);
}
return temp;
}
}
public int factorial(int n){
if(n==0)
return 1;
else{
int result=1;
for(int i=1;i<n;++i)
result*=i;
return result;
}
}
public static void main(String[] args) {
int sum=0;
int temp=0;
for(int i=1;i<=10;i++){
if(i==1){
temp=1;
}
else
temp=temp*i;
System.out.println(temp);
sum=sum+temp;
}
System.out.println("1-10的阶层之和是:"+sum);
}
}
if(n==1)
return 1;
else
return n*factorial(n-1);
}