早教吧 育儿知识 作业答案 考试题库 百科 知识分享

C#写个方法计算1到n的整数中"1"的个数

题目详情
C# 写个方法 计算 1到n的整数 中"1"的个数
▼优质解答
答案和解析
int count = 0, position = 0; //count为1的数量,position为当前位数
for (int i = 0; i < n; i++)
{
int temp = i;
while ((temp / 10 )> 0) //如果除以10大于0,说明为多位数
{
position = temp%10; //判断最低位是否为1
if (position==1)
{
count++;
}
temp /= 10; //向前移一位
}
if (temp == 1) //判断最高位是否为1
{
count++;
}
}
Console.WriteLine(count);
亲测通过,不懂可以再问.