求1~n整数中1出现的次数

下面以1~13为例,其中得到1,10,11,12,13,其中1出现的次数为6;

n的值可以自行定义。 

#include<string>
#include<sstream>
#include<iostream>
using namespace std;
int main()
{
	//求1~n整数中1出现的次数 
	std::stringstream stream;
	std::string result;
	int n=13;
	int count=0;
	while(n>0)
	{
		stream<<n;//将int输入流
		stream>>result;//从stream中抽取前面插入的int值
		//std::cout<<result<<std::endl;//输出string类型的13 
		
		for(int i=0;i<result.length();i++)
		{
			//cout<<result[i]<<" "<<endl;
			if(result[i]=='1')
			count++;
		}
		stream.clear();//清空内容 
		n--;
	}
	cout<<count<<endl;
	return 0;
}
发布了14 篇原创文章 · 获赞 4 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/aaassslll147/article/details/104080040
今日推荐