zoukankan      html  css  js  c++  java
  • 关于有多少个1的计算

    1、题目

    输入一个十进制的数,输出

        (1)、给定n,求出从1到n的所有整数中1的个数。(暂用用f(n)表示)
        (2)、求满足n=f(n)的最小整数(1除外)。

    #include <iostream> 
    #include <math.h> 
    using namespace std; 
     
    void solve(); 
    int input(); 
    int power(int count); 
    void main(){ 
        solve(); 
        system("pause"); 

     
    void solve(){ 
        int n,count=0,i,sum=0; 
        n=input(); 
        //count为一个计数的,来计算n是几位数,如1则为个位数,2则为百位数 
        i=n; 
        while(i){ 
            i=i/10; 
            count++; 
        } 
        while(count--){ 
            i=(n/power(count))%10;//提取了与count对应的位 
            cout<<i<<endl; 
            if(i==1){ 
                if(0==count)//如果对应个位 
                    sum+=1; 
                else 
                    sum+=n%power(count)+1; 
            } 
            else if(i>1){ 
                sum+=power(count); 
            } 
            sum+=n/power(count+1)*power(count); 
        } 
        cout<<"一个有"<<sum<<"个1"<<endl; 

     
    int input(){ 
        cout<<"请输入您想要输入的数字:"<<endl; 
        int n; 
     cin>>n;
     return  n;
    }
     
    int power(int count){ 
        int m=1; 
        if(count<0){ 
            cout<<"count值有误!"<<endl; 
            return -1; 
        } 
        else 
            while(count--) 
                m*=10; 
        return m; 
    }

    把每个位置上的数都分离出来,先确定是几位数,然后在利用每个位置上的数求得出现多少个1 。

    总结:要学会变换思路,以前的时候通过列举找规律,遇到这个问题的时候例句明显太麻烦了,而且很难找到规律,可以找一个数来拆解。

  • 相关阅读:
    django的命令, 配置,以及django使用mysql的流程
    vue中局部组件的使用
    Chapter14【Collection、泛型】
    泛型
    集合遍历的方式(迭代器和增强for)
    Collection集合
    集合
    数组
    包装类
    基本类型与字符串之间的转换
  • 原文地址:https://www.cnblogs.com/jump/p/4548435.html
Copyright © 2011-2022 走看看