Skip to content

Commit 17ec379

Browse files
committed
feat: add python and java solutions to lcof problem
添加《剑指 Offer》题解:面试题64. 求1+2+…+n
1 parent cc6b937 commit 17ec379

File tree

3 files changed

+56
-0
lines changed

3 files changed

+56
-0
lines changed
+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# [面试题64. 求1+2+…+n](https://leetcode-cn.com/problems/qiu-12n-lcof/)
2+
3+
## 题目描述
4+
`1+2+...+n`,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
5+
6+
**示例 1:**
7+
8+
```
9+
输入: n = 3
10+
输出: 6
11+
```
12+
13+
**示例 2:**
14+
15+
```
16+
输入: n = 9
17+
输出: 45
18+
```
19+
20+
**限制:**
21+
22+
- `1 <= n <= 10000`
23+
24+
## 解法
25+
### Python3
26+
```python
27+
class Solution:
28+
def sumNums(self, n: int) -> int:
29+
return n and (n + self.sumNums(n - 1))
30+
```
31+
32+
### Java
33+
```java
34+
class Solution {
35+
public int sumNums(int n) {
36+
int s = n;
37+
boolean t = n > 0 && (s += sumNums(n - 1)) > 0;
38+
return s;
39+
}
40+
}
41+
```
42+
43+
### ...
44+
```
45+
46+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
class Solution {
2+
public int sumNums(int n) {
3+
int s = n;
4+
boolean t = n > 0 && (s += sumNums(n - 1)) > 0;
5+
return s;
6+
}
7+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
class Solution:
2+
def sumNums(self, n: int) -> int:
3+
return n and (n + self.sumNums(n - 1))

0 commit comments

Comments
 (0)