首页 > 其他 > 详细

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

时间:2020-06-02 18:58:20      阅读:35      评论:0      收藏:0      [点我收藏+]

蛮好玩的,很多脑洞,其实都是基础知识

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

原文:https://www.cnblogs.com/xxxsans/p/13032700.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!