zoukankan      html  css  js  c++  java
  • 剑指offer-和为S的连续正数序列-知识迁移能力-python

    题目描述

    小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!

    输出描述:

    输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序

    # -*- coding:utf-8 -*-
    class Solution:
        def FindContinuousSequence(self, tsum):
            # write code here
            l, r, sum, res = 1, 2, 3, []
            while l < r:
                if sum > tsum:
                    sum -= l
                    l += 1
                else:
                    if sum == tsum:
                        res.append([i for i in range(l, r + 1)])
                    r += 1
                    sum += r
    
            return res
    
    print(Solution().FindContinuousSequence(9))
  • 相关阅读:
    逆元(费马小定理求法)
    CodeForces
    lower_bound and upper_bound
    HDU 4825 Xor Sum
    1030: [JSOI2007]文本生成器
    1070: [SCOI2007]修车
    agc 027 B
    P2664 树上游戏
    CF 314 E. Sereja and Squares
    4237: 稻草人
  • 原文地址:https://www.cnblogs.com/ansang/p/12071494.html
Copyright © 2011-2022 走看看