题解 | #求1+2+3+...+n#

求1+2+3+...+n

http://www.nowcoder.com/practice/7a0da8fc483247ff8800059e12d7caf1

1 python解法:幂运算加位运算
# -*- coding:utf-8 -*-
class Solution:
    def Sum_Solution(self, n):
        # write code here
        return ((n**2-n)>>1)+n

2.java解法:也是幂运算加位运算,但是没有python 简洁
public class Solution {
    public int Sum_Solution(int n) {
        return ((((new Double(Math.pow(n,2))).intValue())-n)>>1)+n;
        //return (int((Math.pow(n, 2)-n))>>2)+n;
    }
}


全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务