• 找1


    一、题目:

          给定一个十进制的正整数,写下从1开始,到N的所有整数,然后数一下其中出现“1”的个数。

          要求:写一个函数f(N),返回1到N之间出现1的个数。例如,f(12)=5。

    二、设计思路:

          1、当N>=1时,f(N)=1;N=0时,f(N)=0;    f(2-9)=0;

          2、f (10)=1+1=2

               f(13)=2+5=7  

               f(23)=3+10=13

               f(93)=10+10=20

          3、f(113)=12+14+14=40

       f(123)=个位出现的1数+十位出现的1数+百位出现的1数
     

      4、N = abcde时 以c位为例

        if(c==0)  num=ab*100;

        if(c==1)  num=ab*100+de+1;

        if(c>=2)  num=(ab+1)*100

          ......

          f(abcde),若要计算c位上1的个数,需看ab、c、de的情况。

    三、实验代码

    #include<iostream> 
    #include<math.h> 
    using namespace std; 
      
    int shu1(int num) 
    { 
        int flog=1;//标记计数1的位数(1为个位,10为十位) 
        int now=0;//当前位数
        int low=0;//较低位数 
        int high=0;//较高位数 
        int count=0; 
        while(num/flog!=0) 
        { 
             now=(num/flog)%10; 
            low=num-(num/flog*flog); 
            high=num/(flog*10); 
            if(num<=0) 
                return 0; 
            if(0==now)//当前数字为0时计数 
            { 
                count+=high*flog; 
            } 
            else if(1==now)//当前数字为1时计数 
            { 
                count+=high*flog+low+1; 
            } 
            else
            { 
                count+=(high+1)*flog; 
            } 
            flog=flog*10;//数字左移一位 
        } 
        return count; 
    } 
    void main() 
    { 
        int num; 
        int max=0; 
        cout<<"请输入要测试的数值:"<<endl;
        cin>>num;
        cout<<"出现1的个数为:"<<shu1(num)<<endl; 
    } 
    
    

     四、实验截图

    五、实验总结

    通过此次实验,利用数学找规律,但是可能是草稿纸太乱,思路也跟着乱了,

    所以无论是草稿还是作业,工整才可以思路清晰。

  • 相关阅读:
    对软件测试的理解
    Android 经典欧美小游戏 guess who
    Shell脚本 | 安卓应用权限检查
    自动化测试 | UI Automator 进阶指南
    Shell脚本 | 截取包名
    自动化测试 | UI Automator 入门指南
    杂谈随感 | 与测试无关
    Shell脚本 | 性能测试之内存
    Shell脚本 | 健壮性测试之空指针检查
    "java.lang.IllegalStateException: No instrumentation registered! Must run under a registering instrumentation."问题解决
  • 原文地址:https://www.cnblogs.com/tangxiandi/p/4468683.html
Copyright © 2020-2023  润新知