Number of Digit One
2015-07-28 16:48
429 查看
题目:
Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.
For example:
Given n = 13,
Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.
解题思路:
(1)暴力破解(O(n))-
class Solution:
# @param {integer} n
# @return {integer}
def countDigitOne(self, n):
res = 0
for i in range(1,n+1):
s = str(i)
res = res+s.count('1')
return res
(2)逐位求法
还有一种方法就是数每一个数位上1出现的个数。
对于一个数 abcd
当 d > 1的时候 个位上出现1的个数为 (abc + 1)*1
当d = 1 的时候 个位上出现1的个数为 abc * 1 + 0 + 1, 0表示 d后面的数。对于11 来说,个位上出现1的数为 11,1
当d = 0的时候 个位上出现1的个数为 abc * 1
对于其它数位,相对的1变为10,100,1000..
class Solution:
# @param {integer} n
# @return {integer}
def countDigitOne(self, n):
res = 0
base = 1
before_dig = 0
while n>0:
end_dig = n%10
n = n/10
if end_dig>1:
res = res+(n+1)*base
elif end_dig==1:
res = res+n*base+before_dig+1
else:
res = res+n*base
before_dig = end_dig*base+before_dig
base = base*10
return res
Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.
For example:
Given n = 13,
Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.
解题思路:
(1)暴力破解(O(n))-
Time Limit Exceeded
class Solution:# @param {integer} n
# @return {integer}
def countDigitOne(self, n):
res = 0
for i in range(1,n+1):
s = str(i)
res = res+s.count('1')
return res
(2)逐位求法
还有一种方法就是数每一个数位上1出现的个数。
对于一个数 abcd
当 d > 1的时候 个位上出现1的个数为 (abc + 1)*1
当d = 1 的时候 个位上出现1的个数为 abc * 1 + 0 + 1, 0表示 d后面的数。对于11 来说,个位上出现1的数为 11,1
当d = 0的时候 个位上出现1的个数为 abc * 1
对于其它数位,相对的1变为10,100,1000..
class Solution:
# @param {integer} n
# @return {integer}
def countDigitOne(self, n):
res = 0
base = 1
before_dig = 0
while n>0:
end_dig = n%10
n = n/10
if end_dig>1:
res = res+(n+1)*base
elif end_dig==1:
res = res+n*base+before_dig+1
else:
res = res+n*base
before_dig = end_dig*base+before_dig
base = base*10
return res
相关文章推荐
- AHandler机制
- iOS 检测设备旋转状态
- Python 获取根据文件URL 获取文件的基本信息
- 常用第三方库
- js中字符串的拼接的另一种方法
- ShopNC本地生活o2o网站的源代码,没有域名限制
- Xcode界面简介
- 在移动Web页面中使用CSS固定页脚
- Java制作证书的工具keytool用法总结
- 阿里巴巴-业务型产品经理一面
- 理解 pkg-config 工具
- CHKen Tray Clock 2.68珍藏版 51KB免装 任务栏显秒 定时 报时提醒 流量显示
- poj1637 混合图欧拉回路的求解 网络流
- GET和POST的区别
- UI中获取图片的三种方式
- Raspberry vnc 连接
- 阿里巴巴-业务型产品经理一面
- Codeforces313 Equivalent Strings(DFS)
- 重学java23种设计模式(7)桥接模式
- VM中Ubuntu的VMware-Tools的安装方法