【牛客題解】 ——整數中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;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章