题解 | #求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;
    }
}


全部评论

相关推荐

牛客41406533...:回答他在课上学,一辈子待在学校的老教授用三十年前的祖传PPT一字一句的讲解,使用谭浩强红皮书作为教材在devc++里面敲出a+++++a的瞬间爆出114514个编译错误来学这样才显得专业
点赞 评论 收藏
分享
10-20 11:11
辽宁大学 营销
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务