剑指 Offer 64. 求1+2+…+n

求 1+2+...+n ,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/qiu-12n-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution {

    private int multiply(int a, int b) {
        int ans = 0;
        while (b > 0) {
            if ((b & 1) == 1) {
                ans += a;
            }
            a <<= 1;
            b >>= 1;
        }
        return ans;
    }


    /**
     * (n + 1) * n / 2
     */
    public int sumNums(int n) {
        int ans = 0;
        int a = n, b = n + 1;
        boolean inf = (b & 1) == 1 && (ans += a) > 0;
        a <<= 1;
        b >>= 1;
        inf = (b & 1) == 1 && (ans += a) > 0;
        a <<= 1;
        b >>= 1;
        inf = (b & 1) == 1 && (ans += a) > 0;
        a <<= 1;
        b >>= 1;
        inf = (b & 1) == 1 && (ans += a) > 0;
        a <<= 1;
        b >>= 1;
        inf = (b & 1) == 1 && (ans += a) > 0;
        a <<= 1;
        b >>= 1;
        inf = (b & 1) == 1 && (ans += a) > 0;
        a <<= 1;
        b >>= 1;
        inf = (b & 1) == 1 && (ans += a) > 0;
        a <<= 1;
        b >>= 1;
        inf = (b & 1) == 1 && (ans += a) > 0;
        a <<= 1;
        b >>= 1;
        inf = (b & 1) == 1 && (ans += a) > 0;
        a <<= 1;
        b >>= 1;
        inf = (b & 1) == 1 && (ans += a) > 0;
        a <<= 1;
        b >>= 1;
        inf = (b & 1) == 1 && (ans += a) > 0;
        a <<= 1;
        b >>= 1;
        inf = (b & 1) == 1 && (ans += a) > 0;
        a <<= 1;
        b >>= 1;
        inf = (b & 1) == 1 && (ans += a) > 0;
        a <<= 1;
        b >>= 1;
        inf = (b & 1) == 1 && (ans += a) > 0;
        a <<= 1;
        b >>= 1;
        return ans >> 1;
    }
}
上一篇:Pandas循环提速7万多倍!Python数据分析攻略!


下一篇:【模板】nim 游戏