zoukankan      html  css  js  c++  java
  • PAT甲级1049. Counting Ones

    PAT甲级1049. Counting Ones

    题意:

    任务很简单:给定任何正整数N,你应该计算从1到N的整数的十进制形式的1的总数。例如,给定N为12,在1,10, 11和12。

    思路:

    《编程之美》2.4。
    计算每位出现1的次数。所有的加起来就是答案了。

    • 如果该位为0。如12012的百位数。 说明永远取不到121xx的形式。那么这个就相当于12000以下的数所有的可能。所以就是就是这样的形式 n(1)xx ,n为[0,11]所以就是12 * 100 ,即1200种可能。
    • 如果为1。如12112的百位数。除了之前的1200中,还有121n,n为[0,12]即1212种可能。
    • 如果大于1。比如12212的百位数。除了1200种以外。还有12100~12199的100种。总共1300种。

    ac代码:

    C++

    #include<iostream>
    #include<cstdio>
    #include<string>
    #include<algorithm>
    #include<queue>
    #include<vector>
    #include<cstring>
    #include<stdio.h>
    #include<map>
    #include<cmath>
    #include<unordered_map>
    
    using namespace std;
    
    int main()
    {
    	int nums;
    	scanf("%d", &nums);
    
    	//handle problem
    	int res = 0,temp,index = 1,low = 0;
    	while (nums)
    	{
    		temp = nums % 10;
    		nums /= 10;
    		if (temp == 0) res += nums * index;
    		else if (temp == 1) res += nums*index + low + 1;
    		else res += (nums + 1) * index;
    		low += temp * index;
    		index *= 10;
    	}
    
    
    	//output
    	printf("%d
    ", res);
        return 0;
    }
    
    
  • 相关阅读:
    洛谷 U141580 简化罗波切问题
    洛谷 U141578 维修电路
    洛谷 U140760 狭义公因子
    CF75C Modified GCD
    算法题-求解斐波那切数列的第N个数是几?
    算法题-求N的阶乘
    JAVA8新特性
    nginx启动脚本,手动编辑
    javah生成带有包名的头文件
    Matlab图像处理(03)-基本概念
  • 原文地址:https://www.cnblogs.com/weedboy/p/7279814.html
Copyright © 2011-2022 走看看