整数个数C++
描述
输入一串带有整数的字符串,输出其中连续的数字(一个数字也算)组成的整数有多少个?
例如,输入字符串“a123b012c”,其中连续的整数有123、12(前面多余0可以认为没有,如果连续的0或者单独一个0,也算一个整数)两个,所以输出2
输入描述
一行字符串,长度小于256
输出描述
输出其中整数的个数
用例输入 1
a123b012c
用例输出 1
2
没明白求解
#include <stdio.h>
int main()
{
char ch[260];
scanf("%s", &ch[0]);
int st = 0;
int cnt = 0;
for (int i = 0; ch[i]; i++)
{
if (st == 0 && ch[i] >= '0' && ch[i] <= '9')
{
st = 1; cnt++;
}
else if (st == 1 && (ch[i] < '0' || ch[i] > '9')) st = 0;
}
printf("%d", cnt);
return 0;
}
好题目
#include <iostream>
#include "math.h"
#include <vector>
#include <string>
using namespace std;
int main()
{
string s;
cin>>s;
int numberCount=0; //记录总数
string s1; //用于判断连续数字
for(int i=0;i<s.size();++i)
{
char ch=s[i];
if(ch>='0'&&ch<='9')
{
s1.push_back(ch);
}
else
{
if(s1!="")
{
numberCount++;
s1.clear();
}
}
}
cout<<"numberCount = "<<numberCount<<endl;
return 0;
}