LeetCode 剑指 Offer 64. 求1+2+…+n
题目描述
求 1+2+...+n ,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
原题连接
链接:https://leetcode-cn.com/problems/qiu-12n-lcof/
一、基础框架
class Solution {
public int sumNums(int n) {
}
}
二、解题报告
1.思路分析
1、第一时间想到循环,因为需要处理所有的数据
2、除去循环之外,可以使用递归和三目运算进行数据处理
2.时间复杂度
3.代码示例
tips:
class Solution {
public int sumNums(int n) {
// int sum = 0;
// for(int i = 1; i <= n; i ++){
// sum +=i;
// }
// return sum;
boolean flag = n > 0 && (n += sumNums(n - 1)) > 0;
return n;
}
}
2.知识点
本文介绍了一种解决LeetCode剑指Offer64.求1+2+…+n问题的方法,该方法避免了使用循环、条件判断等关键字。通过巧妙运用递归调用和三目运算符,实现了对1到n之间所有整数的求和。
508

被折叠的 条评论
为什么被折叠?



