1 題目描述
求 1+2+…+n ,要求不能使用乘除法、for、while、if、else、switch、case等關鍵字及條件判斷語句(A?B:C)。
示例 1:
輸入: n = 3
輸出: 6
示例 2:
輸入: n = 9
輸出: 45
限制:
1 <= n <= 10000
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/qiu-12n-lcof
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
2 解題思路
大佬的解法真的是出奇,非常詳細也非常具體
面試題64. 求 1 + 2 + … + n(邏輯符短路,清晰圖解)
- 方法三: 遞歸
問題: 終止條件需要使用 if ,因此本方法不可取。
思考: 除了 if 和 switch 等判斷語句外,是否有其他方法可用來終止遞歸?
public int sumNums(int n) {
if(n == 1) return 1;
n += sumNums(n - 1);
return n;
}
- 方法:邏輯符短路
- 代碼:
(1)Java 中,爲構成語句,需加一個輔助布爾量 x ,否則會報錯;
(2)Java 中,開啓遞歸函數需改寫爲 sumNums(n - 1) > 0 ,此整體作爲一個布爾量輸出,否則會報錯;
(3)初始化變量 res 記錄結果。
作者:jyd
鏈接:https://leetcode-cn.com/problems/qiu-12n-lcof/solution/mian-shi-ti-64-qiu-1-2-nluo-ji-fu-duan-lu-qing-xi-/
來源:力扣(LeetCode)
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。
3 解決代碼
- 方法:邏輯符短路《Java代碼》
class Solution {
int res = 0;
public int sumNums(int n) {
boolean x = n > 1 && sumNums(n - 1) > 0;
res += n;
return res;
}
}
- 方法:邏輯符短路《python3代碼》
class Solution:
def __init__(self):
self.res = 0
def sumNums(self, n: int) -> int:
n > 1 and self.sumNums(n - 1)
self.res += n
return self.res