之前去一家软件公司笔试,看到标题所列题目,平时自己喜欢逛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;