leetcode面试题64. 求1+2+…+n
蛮好玩的,很多脑洞,其实都是基础知识
c++
逻辑运算符替代判断语句+递归
class Solution { public: int sumNums(int n) { n && (n += sumNums(n-1)); return n; } };
手动展开快乘循环
int qPow(int a, int b) { int ans = 0; for ( ; b; b >>= 1) { if (b & 1) { ans += a; } a <<= 1; } return ans; }
得
class Solution { public: int sumNums(int n) { int ans = 0, A = n, B = n + 1; (B & 1) && (ans += A); A <<= 1; B >>= 1; (B & 1) && (ans += A); A <<= 1; B >>= 1; (B & 1) && (ans += A); A <<= 1; B >>= 1; (B & 1) && (ans += A); A <<= 1; B >>= 1; (B & 1) && (ans += A); A <<= 1; B >>= 1; (B & 1) && (ans += A); A <<= 1; B >>= 1; (B & 1) && (ans += A); A <<= 1; B >>= 1; (B & 1) && (ans += A); A <<= 1; B >>= 1; (B & 1) && (ans += A); A <<= 1; B >>= 1; (B & 1) && (ans += A); A <<= 1; B >>= 1; (B & 1) && (ans += A); A <<= 1; B >>= 1; (B & 1) && (ans += A); A <<= 1; B >>= 1; (B & 1) && (ans += A); A <<= 1; B >>= 1; (B & 1) && (ans += A); A <<= 1; B >>= 1; return ans >> 1; } };
python
class Solution: def sumNums(self, n: int) -> int: return sum(range(n+1))
Java
class Solution { int[] test=new int[]{0}; public int sumNums(int n) { try{ return test[n]; }catch(Exception e){ return n+sumNums(n-1); } } }
class Solution { public int sumNums(int n) { return IntStream.range(1,n+1).sum(); } }