剑指offer 47. 求1 + 2 + 3 + .... + n

47. 求1 + 2 + 3 + .... + n

题目描述

求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。

思路一:

使用 && 运算符实现 if(n != 0)条件判断,因为 Java 的双与运算符左右两边都必须是 boolean 类型,所以右边加一个 “== 0”, 并且 Java 的表达式不能单独存在,所以把 && 的结果返回给一个变量

1 public class Solution {
2     public int Sum_Solution(int n) {
3         int sum = n;
4         boolean flag = ((n != 0) && (sum += Sum_Solution(n - 1)) == 0);
5         return sum;
6     }
7 }

思路二:

利用求和公式和 pow() 函数

1 + 2 + ... + n = n * (n + 1) / 2 = (n^2 + n) / 2

所以 1 + 2 + ... + n = ( pow(n, 2) + n) / 2;

1 public class Solution {
2     public int Sum_Solution(int n) {
3        return (int)(Math.pow(n, 2) + n) / 2;
4     }
5 }

猜你喜欢

转载自www.cnblogs.com/hi3254014978/p/12628625.html