class Solution:
def sumNums(self, n: int) -> int:
n = n and n + self.sumNums(n - 1)
return n
if __name__ == '__main__':
solution = Solution()
res = solution.sumNums(3)
print(res)
class Solution:
def sumNums(self, n: int) -> int:
ans, a, b = 0, n, n + 1
# 0
ans = (not b & 1 and ans) or (b & 1 and ans + a)
b >>= 1
a <<= 1
# 1
ans = (not b & 1 and ans) or (b & 1 and ans + a)
b >>= 1
a <<= 1
# 2
ans = (not b & 1 and ans) or (b & 1 and ans + a)
b >>= 1
a <<= 1
# 3
ans = (not b & 1 and ans) or (b & 1 and ans + a)
b >>= 1
a <<= 1
# 4
ans = (not b & 1 and ans) or (b & 1 and ans + a)
b >>= 1
a <<= 1
# 5
ans = (not b & 1 and ans) or (b & 1 and ans + a)
b >>= 1
a <<= 1
# 6
ans = (not b & 1 and ans) or (b & 1 and ans + a)
b >>= 1
a <<= 1
# 7
ans = (not b & 1 and ans) or (b & 1 and ans + a)
b >>= 1
a <<= 1
# 8
ans = (not b & 1 and ans) or (b & 1 and ans + a)
b >>= 1
a <<= 1
# 9
ans = (not b & 1 and ans) or (b & 1 and ans + a)
b >>= 1
a <<= 1
# 10
ans = (not b & 1 and ans) or (b & 1 and ans + a)
b >>= 1
a <<= 1
# 11
ans = (not b & 1 and ans) or (b & 1 and ans + a)
b >>= 1
a <<= 1
# 12
ans = (not b & 1 and ans) or (b & 1 and ans + a)
b >>= 1
a <<= 1
# 13
ans = (not b & 1 and ans) or (b & 1 and ans + a)
return ans >> 1
if __name__ == '__main__':
solution = Solution()
res = solution.sumNums(5)
print(res)
补充:
(1) 本题的难点在于对于运算符的使用
- 对于
if...elif...elif...
, 使用or连接多种情况,使用and连接每一种情况的条件和执行体,最后对每一个条件进行斟酌。如
相当于ans = (not b & 1 and ans) or (b & 1 and ans + a)
if not b & 1: ans = ans elif not b& 1: ans = ans + a
(2) python中没有xor逻辑运算符,只有xor位运算符"^"。但逻辑运算符有个等式:
- a⊕b = (¬a ∧ b) ∨ (a ∧¬b)
[参考博客]
求1+2+…+n