C++ 求解一道题 给出任意一个整数n,计算出 从1到n中所有数中1出现的次数 求大神帮忙

2025年03月13日 00:48
有4个网友回答
网友(1):

#include

#include

#include



using namespace std;


int main()

{

cout<<"input the n "<

int n;

cin>>n;

    for(int i=1;i

    {

    ostringstream os;

    os<

    string temp=os.str();

     int count=0;

    for(int j=0;j

    {

      if(temp[j]=='1')

      count++;


    }

    cout<

    }

    cout << "Hello world!" << endl;

    return 0;

}

网友(2):

重点学习取出每一位的过程,莫只是抄了了事。


#include 
int main ()
{
int n;
cout<<"pls input n";
cin>>n;
int s[10]={0};//存储每个数字出现个数
for(int i=1;i<=n;i++)
{
//连续从后边取出一位进行计数
int shang,yushu;
shang=i;
while(shang!=0)
{
yushu=shang%10;
s[yushu]++;
shang=shang/10;
}
}
//输出结果
cout<}

网友(3):

楼主采纳我的吧,我的比较精妙

#include "iostream.h"
int main()
{

int n,i;
cin>>n;
int count = 0;
int seed[10] = {0,1,0,0,0,0,0,0,0,0};
for (i=0;i<=n;++i)
{
count += seed[i % 10];
count += seed[i % 100 / 10];
count += seed[i % 1000 / 100];
count += seed[i % 10000 / 1000];
count += seed[i % 100000/ 10000];

}
count += 1;
cout<
}

网友(4):

#include
int main()
{
int n ;
int cnt=0;
scanf("%d" , &n );
for( i=1;i<=n;i++ )
{
int x=i ;
while( x )
{
if ( x%10 == 1)
cnt++ ;
x/=10 ;
}
}
printf("cnt1=%d\n",cnt);
return 0;
}