剑指offer-47.求1+2+3+...+n

xiaoxiao2021-02-28  102

题目:求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。

思路:刚开始一想到的就是递归,但是好像一般递归都有if else ?怎么办,短路求值,就不需要用了if判断了,相与或者相或本身就具有判断的意思。

你没猜错, n == 0 || (res = Sum_Solution(n - 1) );当两个结果都为0时跳出循环

class Solution { public: int Sum_Solution(int n) { int res = 0; n == 0 || (res = Sum_Solution(n - 1) ); return n + res; } };

转载请注明原文地址: https://www.6miu.com/read-62642.html

最新回复(0)