20191019-求含8数字

2018奥赛初赛题(5)

题目:

从1到2018这2018个数中,共有  544    个包含数字8的数。含数字8的数是指某一位是“8”的数,例如“2018”与“188。”

解题思路:

A方案:

将这2018个数字分别变成字符串,然后在每个字符串中,用find()方法找"8"(即看这个数是否含有"8",找到一个就行)。

  1. #include "stdafx.h"

  2. #include "cstdio"

  3. #include "string"

  4. #include "cstring"

  5. #include "iostream"

  6. using namespace std;

  7. string a="";

  8. int main()

  9. {

  10.   int count=0;

  11.  for(int i=1;i<=2018;i++)

  12.   {

  13.      a=to_string(i);

  14.     if(a.find("8")!=-1)//-1代表找不到

  15.       count+=1;

  16. }

  17. cout<<"共有"<<count<<"个"<<endl;

  18. }

运行结果:

B方案:

取余,看是否余数是否是8。

  1. #include "stdafx.h"

  2. #include "cstdio"

  3. int main()

  4. {

  5.   int count=0;

  6.  for(int i=1;i<=2018;i++)

  7.   {

  8.      if(i%10==8 || i/10%10==8 || i/100%10==8)//个位数有8适用 i%10==8, 十位数有8适用 i/10%10==8 , 百位数有8适用 i/100%10==8

  9.       count+=1;

  10. }

  11. cout<<"共有"<<count<<"个"<<endl;

  12. }

运行结果: 

posted @ 2020-05-21 10:28  财盛  阅读(814)  评论(0编辑  收藏  举报