黑马程序员----计算1到n的数字中一共有多少1?最效率的方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace doomsday
{
static long CountOne(long n)
{
long count = 0;
long i = 1;
long current = 0, after = 0, before = 0;
while ((n / i) != 0)
{
current = (n / i) % 10;
before = n / (i * 10);
after = n - (n / i) * i;
if (current > 1)
count = count + (before + 1) * i;
else if (current == 0)
count = count + before * i;
else if (current == 1)
count = count + before * i + after+ 1;
i = i * 10;
}
return count;
}
static void Main(string[] args)
{
Console.WriteLine(CountOne(9999999999999));
Console.ReadKey();
}
}
有很多方法解决这个问题,我觉得这个效率不错。