题解 | #求1+2+3+...+n#
求1+2+3+...+n
https://www.nowcoder.com/practice/7a0da8fc483247ff8800059e12d7caf1
不让循环那就递归,不让判断那就赋值。
python3的特点(其他语言应该也类似):
0 and 3, 返回0;1 and 3,返回3。
也就是说使用and,前面截断则直接截断,前面成立,后面才会计算。
or逻辑符也类似。class Solution: def __init__(self): self.res = 0 def Sum_Solution(self , n: int) -> int: # n为0直接截断,即终止递归。代替了if等语句的作用。 _ = n and self.Sum_Solution(n-1) self.res += n return self.res
方法无非是乘法或者循环或者递归,都是为了代替手动迭代。
因为0 < n ≤ 200 = 0b11001000,最长也就8位,所以可以手动写8次迭代(对n迭代n+1次,n+1二进制分解):每次迭代:判断n+1的最低位是0还是1:如果是1,就把n左移1位,然后把n+1右移一位 Python 3.8 版本引入了海象运算符 :=,可以在不允许赋值的地方(如条件表达式中)使用赋值变量
class Solution: def Sum_Solution(self , n: int) -> int: res, a, b = 0, n, n + 1 _ = (b & 1) and (res := res + a) a <<= 1 b >>= 1 _ = (b & 1) and (res := res + a) a <<= 1 b >>= 1 _ = (b & 1) and (res := res + a) a <<= 1 b >>= 1 _ = (b & 1) and (res := res + a) a <<= 1 b >>= 1 _ = (b & 1) and (res := res + a) a <<= 1 b >>= 1 _ = (b & 1) and (res := res + a) a <<= 1 b >>= 1 _ = (b & 1) and (res := res + a) a <<= 1 b >>= 1 _ = (b & 1) and (res := res + a) a <<= 1 b >>= 1 return res >> 1