題目
求 1+2+…+n ,要求不能使用乘除法、for、while、if、else、switch、case等關鍵字及條件判斷語句(A?B:C)。
示例 1:
輸入: n = 3
輸出: 6
示例 2:
輸入: n = 9
輸出: 45
限制:
1 <= n <= 10000
鏈接:https://leetcode-cn.com/problems/qiu-12n-lcof
解題記錄
一開始看題目,以爲只要不用if,else啥的就行,直接通過算面積的方法就行:
/**
* @author ffzs
* @describe 面試題64. 求1+2+…+n
* @date 2020/6/2
*/
public class Solution {
public int sumNums(int n) {
return (n+1)*n/2;
}
}
但是一想是中等難度,這樣也太簡單了,又仔細看了一下題目,也要求不能用乘除法。。
邏輯運算符的短路效應
對於邏輯判斷中有短路效應:
if(A && B) // 若 A 爲 false ,則 B 的判斷不會執行(即短路),直接判定 A && B 爲 false
if(A || B) // 若 A 爲 true ,則 B 的判斷不會執行(即短路),直接判定 A || B 爲 true
本題如果使用遞歸的話需要使用if判斷跳出,但是題目並不允許,因此可以使用上面的短路效應
/**
* @author ffzs
* @describe 面試題64. 求1+2+…+n
* @date 2020/6/2
*/
public class Solution {
public static int sumNums(int n) {
boolean x = n > 1 && (n += sumNums(n - 1)) != 0;
return n;
}
}