zoukankan      html  css  js  c++  java
  • 统计1的个数

    #include <iostream>
    #include <string>
    using namespace std;
    
    /************************************************************************/
    /* 输入一个数字N,计算从1到N 这N个数字中1出现的次数
    例如
    N = 2,   则1 2中1出现的次数为1
    N = 12, 则 1 2 3 4 5 6 7 8 9 10 11 12 中1出现的次数为5。
    求任意给一个N返回1的个数。
    1、暴力解法,从1遍历到N,求出每一个数字中1的个数,然后相加之和即为总共1的个数。
    2、分析:分析每一位出现1的次数,总和即为总共1出现的次数
    
    1位数时,N>=1, f(N)=1 当N<1 ,f(N)=0;
    2位数时,假设ab为一个二位数;
    分析个位b:个位1的个数为 a
    分析十位a:十位1的个数,若a=1, 十位1的个数为b+1,若a>1,则十位1的个数为10
    
    
    */
    /************************************************************************/
    /*
    输入一个整数N,求1 2 3 。。。N中含有1的个数
    */
    int countOnes(int N)
    {
        int iCount = 0;
        int iFactor = 1;
        int iLowerNum = 0;
        int iCurrNum = 0;
        int iHigherNum = 0;
        while(N/iFactor)
        {
            iLowerNum = N - (N/iFactor)*iFactor;
            iCurrNum = (N/iFactor)%10;
            iHigherNum = N/(iFactor*10);
            switch(iCurrNum)
            {
            case 0:
                iCount += iHigherNum*iFactor;
                break;
            case 1:
                iCount += iHigherNum*iFactor + iLowerNum +1;
                break;
            default:
                iCount += (iHigherNum+1)*iFactor;
                break;
            }
            iFactor *= 10;
        }
        return iCount;
    }
    
    int main(int argc, char **argv)
    {
        int N;
        cin>>N;
        cout<<countOnes(N)<<endl;
    
        return 0;
    }
  • 相关阅读:
    Nhibernate对象转JSON
    C# Windows服务
    C# 接收http请求
    C# XML 基础解系
    C# XML 序列化与反序列化
    C# Newtonsoft.Json 应用
    C# 读取自定义XML
    对图片添加水印
    iText: 对pdf文件添加水印
    java对Office文件处理技术(介绍)
  • 原文地址:https://www.cnblogs.com/newpanderking/p/3952159.html
Copyright © 2011-2022 走看看