• 为了依次求个位,十位,百位中1的个数,我们可以把这个数字分为三部分,高位数字,当前位数字,低位数字。
  • 如果当前位为0,那么此位为1的数目与高位数字有关
  • 如果当前位为1,那么此位为1的数目与高位和地位都有关
  • 如果当前位其他,那么此位为1的数目与高位数字有关
  • 具体规律看源代码
#include <iostream>

using namespace std;

int main() {
    int N;
    cin >> N;
    int factor = 1;
    int count = 0;
    while (N / factor != 0) {
        int highNum = N / (factor * 10);
        int curNum = (N / factor) % 10 ;
        int lowNum = N - (N / factor) * factor;

        switch(curNum) {
            case 0:
                count += highNum * factor;
                break;

            case 1:
                count += highNum * factor + lowNum + 1;
                break;
            default:
                count += (highNum + 1) * factor;
        }
        factor *= 10;
    }
    cout << count << endl;
    return 0;
}

相关文章:

  • 2022-03-05
  • 2021-10-30
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-22
  • 2021-05-14
  • 2022-12-23
猜你喜欢
  • 2021-09-11
  • 2021-08-26
  • 2021-05-21
  • 2021-07-26
  • 2022-12-23
  • 2021-08-17
  • 2021-11-08
相关资源
相似解决方案