Offer 43. 1~n整数中1出现的次数+有多少个1系列?
发布日期:2021-06-29 18:53:14 浏览次数:2 分类:技术文章

本文共 1398 字,大约阅读时间需要 4 分钟。

文章目录

Offer 43. 1~n整数中1出现的次数

class Solution {
public: int exp10(int pow) {
int result=1; while(pow>0) {
result *=10; pow--; } return result; } int high(int n)//这个数字最高是几位:如256是3位,7865是4位!! {
int result =0; while(n) {
n=n/10; result++; } return result; } int countDigitOne(int n) {
int iter_number = n;//当前的数字 int iter_high = high(n)-1;//代表当前需要/10^iter2来得到他的最高位 int result =0; while(iter_number!=0) {
int temp = iter_number/(exp10(iter_high));//最高位是几 if(temp==1) {
result+=iter_number-exp10(iter_high)+1; } else {
result+=exp10(iter_high); } result+=(iter_high)*exp10(iter_high-1)*temp; // iter_number = iter_number%(exp10(iter_high)); iter_high = high(iter_number)-1; } return result; }};

我是多么的傻逼

  • 曾经,我遇到了一个事情
  • 比2345少1个数量级的数是346
  • 这个简单,我可以很容易就会了

2345%1000即可!

  • 那2034呢?
  • 比他少一个数量级的数是多少呢?
  • 那还是
  • 2034/1000 = 34呀!

1~9999有多少个1?

  • 显然是4位
  • 4 × 1 0 3 = 4000 4\times 10^3=4000 4×103=4000

1~21345有多少个1?

  • 1~9999有4000个1
  • 10000~19999有多少个1?

10~109有多少个1?

  • 这里总共100个数

  • 1的分两部分,一个是高位引起的,
  • 然后是其他位引起的。

  • 首先百位是1的肯定有10个
  • 那个位和十位的1一共多晒个呢?
    • 其实就是1~99中1的个数
    • 共20个1
  • 所以总共30个1

转载地址:https://cyj666.blog.csdn.net/article/details/108308495 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:C++ 多态的定义及实现
下一篇:四:常用算法---排序

发表评论

最新留言

感谢大佬
[***.8.128.20]2024年04月20日 13时05分26秒