算法学习九----在从1到n的正数中1出现的次数

题目:输入一个整数n,求从1到n这n个整数的十进制表示中1出现的次数。

例如输入12,从1到12这些整数中包含1 的数字有1,10,11和12,1一共出现了5次。

要在一个数字中找到1的个数,可以简单地把数字转换成字符串,然后扫描字符串,判断每个字符是否为1,如果为1就把1的个数加1.

另一种解法是通过除法和取模判断1的个数。首先,当数字为1位数时,将其除以10取模,然后判断是否为1,如果为1,就将1的个数相加。如果数字为多为数,则将其不断除以10,如果结果为1,则1的个数加1,直到数字个数为1.


算法伪代码如下:

assign value from 1 to n arr

//count the number of one from 1 to n
for i <- 0 to n
     temp = arr[i];

     while(temp/10 != 0)
     if temp/10 == 1     
          then add sum
     temp /= 10;

if arr[i]%10 == 1
     then add sum

C++实现

int CountOne(const int &n)
{
    int arr[n];
    int sum = 0;
    int temp = 0;

    //assign value from 1 to n arr
    for(int i = 0; i != n; ++i)
    {
        arr[i] = i+1;
    }

    //count the number of one from 1 to n
    //for i <- 0 to n
    for(int i = 0; i != n; ++i)
    {
        temp = arr[i];
        while(temp/10 != 0)
        {
            //if temp/10 == 1
            if(temp / 10 == 1)
            {
                //then add sum
                ++sum;
            }
            temp /= 10;
        }
        
        //if arr[i]%10 == 1
        if(arr[i] % 10 == 1)
        {
            //then add sum
            ++sum;
        }
    }

    return sum;
}

请多多指教!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值