leetcode面试题64. 求1+2+…+n

Posted xxxsans

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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();
    }
}

 

以上是关于leetcode面试题64. 求1+2+…+n的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode]面试题64. 求1+2+…+n

[LeetCode]面试题64. 求1+2+…+n

leetcode面试题64. 求1+2+…+n

leetcode面试题64. 求1+2+…+n

[LeetCode] 面试题64. 求1+2+…+n

[LeetCode] 面试题64. 求1+2+…+n