OJ:PAT A1049 Counting Ones - 数学

本文解析了一个编程问题,涉及统计给定数字中每个数位上1出现的次数。通过理解数字位值处理逻辑,展示了如何用C++代码实现这个计数任务,重点在于处理个位、十位、百位和千位的不同计数规则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这道题的思考过程不难,只要看过就能理解这个过程,从而代码实现出来。题目本身很新颖,但背后也没有特别深刻的思想体系。

这道题的核心是:针对个、十、百、千每一位出现1的次数,对数字1进行统计。然后只要在纸上写一下每一位1的个数是怎么统计的,就知道如何写统计的代码了。

具体的逻辑是要看这一位的值,如果小于1或大于1,则这一位1的个数是整的,由高位;如果是1则要额外考虑高位相等同位是1的数的个数,这个个数由低位确定。

#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <stack>
#include <queue>
#include <vector>
#include <cmath>
#include <cstdio>
#include <bitset>
using namespace std;

const int MAX = 100005;
const int INF = 0x3f3f3f3f;

int count_num(int n_in, int num){
    int n = n_in;
    int result = 0;
    int ten = 1;
    while(n > 0){
        int tail = n % 10;
        n /= 10;
        if(tail < num){
            result += n * ten;
        }
        else if(tail == num){
            result += n * ten + (n_in - n * ten * 10 - ten + 1);
        }
        else{
            result += (n + 1) * ten;
        }
        ten *= 10;
    }
    return result;
}

int count1(int n){
    return count_num(n, 1);
}

int main(){
    int n;
    cin >> n;
    cout << count1(n);
    return 0; 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值