求1到100的和
求1+2+3+...+n
http://www.nowcoder.com/questionTerminal/7a0da8fc483247ff8800059e12d7caf1
乘除法:
public class Solution { public int Sum_Solution(int n) { int sum=0; sum=(1+n)*n/2; return sum; } }
时间复杂度:O(1)
空间复杂度:O(1)
for循环法:
public class Solution { public int Sum_Solution(int n) { int sum=0; for(int i=1;i<=n;i++){ sum+=i; } return sum; } }
时间复杂度:O(n)
空间复杂度:O(1)
while循环法:
public class Solution {
public int Sum_Solution(int n) {
int sum=0;
int i=1;
while(i<=n){
sum+=i;
i++;
}
return sum;
}
}
递归法:
public class Solution {
public int Sum_Solution(int n) {
if(n==1){
return 1;
}else{
return n+Sum_Solution(n-1);
}
}
}