剑指 Offer 64. 求1+2+…+n(限制版)
原理:逻辑运算符的短路效应
常见的逻辑运算符有三种,即 “与 && ”,“或 || ”,“非 ! ” ;他们都具备短路效应,如下所示:
if(A && B) // 若 A 为 false ,则 B 的判断不会执行(即短路),直接判定 A && B 为 false if(A || B) // 若 A 为 true ,则 B 的判断不会执行(即短路),直接判定 A || B 为 true
思路:
可以使用逻辑运算符的短路效应,作为递归运算的终止手段。
代码:
class Solution { int res = 0; public int sumNums(int n) { boolean x = n > 1 && sumNums(n - 1) > 0;//当 n = 1 时 n > 1 不成立 ,此时 “短路” ,终止后续递归 res += n; return res; } } 参考:https://leetcode-cn.com/problems/qiu-12n-lcof/solution/mian-shi-ti-64-qiu-1-2-nluo-ji-fu-duan-lu-qing-xi-/ 来源:力扣(LeetCode)