• 【PAT(甲级)】1049 Counting Ones(与位数以及位数上的数字有关)


    The task is simple: given any positive integer N, you are supposed to count the total number of 1's in the decimal form of the integers from 1 to N. For example, given N being 12, there are five 1's in 1, 10, 11, and 12.

    Input Specification:

    Each input file contains one test case which gives the positive N (≤230).

    Output Specification:

    For each test case, print the number of 1's in one line.

    Sample Input:

    12

    Sample Output:

    5

    解题思路:

    我们统计“1”的个数,可以统计每个位上“1”出现的次数。

    比如说题目中的“12”:

    个位数上的“1”{1,11}出现两次;

    十位数上的“1”{10,11,12}出现三次;

    所以总计五次。

    而每个位上出现“1”的次数,与这个数在这位上的数字有关。

    那么根据规律我们可以得出(如果前面没有数字则默认为0):

    1.         该位上的数字小于1,则它前面的数字,即为“1”出现的次数。例如:“21340”中个位为“0”小于1,则个位上“1”出现的次数为2134次;

    2.        若该位上的数字等于1,则(它前面的数字乘以该位位数+该位后面的数字+1)即为该位上“1”出现的次数。例如:“21340”中千位上为“1”,则千位上“1”出现的次数为(2*1000+340+1)次。

    3.        若该位上的数字大于1,则(该位前面的数+1)*该位位数,即为该位上“1”出现的次数。例如:“21340”中十位上为“4”,则十位上“1”出现的次数为(213+1)*10;百位上为“3”则百位“1”出现的次数为(21+1)*100.

    代码:

    1. #include
    2. using namespace std;
    3. int turn_int(string a){
    4. return atoi(a.c_str());
    5. }
    6. int main(){
    7. long long int N;
    8. cin>>N;
    9. int sum = 0;
    10. int left,right,now,tip = 1;
    11. while(N/tip!=0){
    12. left = N / (tip*10);
    13. right = N % tip;
    14. now = N / tip % 10;
    15. if(now == 0) sum += left*tip;
    16. else if(now == 1) sum += left*tip + right + 1;
    17. else sum += (left+1) * tip;
    18. tip *= 10;
    19. }
    20. cout<
    21. return 0;
    22. }

  • 相关阅读:
    java计算机毕业设计同学录管理系统源码+系统+数据库+lw文档+mybatis+运行部署
    软件下载站
    HTML 13 HTML a 标签
    央企施工企业数字化转型的灵魂是什么
    Flask框架学习大纲
    「干货」从动态的角度分析DDR的时序结构
    【推搜】embedding评估 | faiss的topK向量检索
    万物数创CTO黄一:别人批判我的代码是件有趣的事 | 对话MVP
    AndroidT(13) -- logger_write 库实现解析(四)
    @PostConstruct注解详解
  • 原文地址:https://blog.csdn.net/weixin_55202895/article/details/126561621