【牛客题解】 ——整数中1出现的次数

整数中1出现的次数

在这里插入图片描述
思路一:迭代

class Solution {
public:
    int NumberOf1Between1AndN_Solution(int n)
    {
        int count=0;
        for(int i=1;i<=n;i++)
        {
            int temp=i;
           while(temp>0)
          {
              if(temp%10==1)
              {
                  count++;
              }
               temp/=10;
          }
        }
       return count; 
    }
};

思路2:利用stringstream将数字转化为字符串

class Solution {
public:
    int NumberOf1Between1AndN_Solution(int n)
    {
        int count=0;
        for(int i=1;i<=n;i++)
        {
            string res;
            stringstream ss;
            ss<<i;  //将i转化成流ss
            ss>>res;//再将流ss转化成字符串
            for(int j=0;j<res.size();j++)
            {
                if(res[j]=='1')
                    count++;
            }
        }
        return count;
    }
};
原创文章 78 获赞 21 访问量 3548

猜你喜欢

转载自blog.csdn.net/Vicky_Cr/article/details/105485464