统计从1到n的正整数中1出现的次数...

之前去一家软件公司笔试,看到标题所列题目,平时自己喜欢逛CSDN论坛,曾浏览过相关的其他编程语言编写的帖子,奈何自己没有仔细研究,只知道方法是先计算出每个位上1出现的次数,然后相加,因笔试时间有限制,自己就用了遍历的方法:
function Get1ToN1ExistSum1(n: Integer): Integer;
var
  Sum: Integer;
  I: Integer;
  function get1ExistSum(n: Integer): Integer;
  var
    sum: Integer;
  begin
    Sum := 0;
    while (n <> 0) do
    begin
      if (n mod 10) = 1 then Sum := Sum + 1;
      n := n div 10;
    end;
    Result := Sum;
  end;
begin
  Sum := 0;
  for I := 1 to n do
  begin
    Sum := Sum + get1ExistSum(I);
  end;
  Result := Sum;
end;
笔试结束后,回去等通知,又跑去浏览了一遍那篇C语言写的帖子,用Delphi将那个算法翻译如下:
 
function Get1ToN1ExistSum2(n: Integer):Integer;
var
  I, iCount, iFactor: Integer;
  CurrCount, Low, High: Integer;
begin
  CurrCount:= 0;
  Low := 0;
  High:= 0;
  iCount := 0;
  iFactor := 1;
  while (n div iFactor <> 0) do
  begin
    Low := n - (n div iFactor)*iFactor;
    CurrCount := (n div iFactor) mod 10;
    High := n div (iFactor * 10);
    Case CurrCount of
    0: iCount := iCount + High * iFactor;
    1: iCount := iCount + High * iFactor + Low + 1;
    else
       iCount := iCount + (High + 1)*iFactor;
    end;
    iFactor := (iFactor * 10);
  end;
  Result := iCount;
end;

                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值