题解 | #整数中1出现的次数(从1到n整数中1出现的次数)#

整数中1出现的次数(从1到n整数中1出现的次数)

http://www.nowcoder.com/practice/bd7f978302044eee894445e244c7eee6

# 两种python解法 
# @param n int整型 
# @return int整型

class Solution:
    def f1(self,n): #第一种转化为字符串来求解
        count=0
        for i in range(1,n+1):
            for j in str(i): #获取在不同位数上的'1'个数
                if '1'== j:
                    count+=1
        return count
    
    def f2(self,n):#依次获取高低位含1的个数
        count = 0
        i = 1
        while i <= n:
            high = n//(i*10)*i  # 高位
            low = min(max(n % (i*10)-i+1, 0), i)  # 低位
            count += high+low
            i *= 10  # 每个位数上找一遍
        return count
    def NumberOf1Between1AndN_Solution(self , n: int) -> int:
        # write code here
        if not n:
            return 0
        #return self.f1(n)
        return self.f2(n)

全部评论

相关推荐

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