Task
Viết chương trình để tính tổng các số có xuất hiện trong xâu s cho trước.
Input • Gồm một xâu duy nhất s có chứa các chữ cái và số có độ dài không quá 500 ký tự.
Output • In ra tổng các số có chứa trong xâu.
Samples
input 5 random strings contain 234 numbers
output 239
Code:
Cach1:
#include <bits/stdc++.h>
using namespace std;
int main(){
int min=1000,tong = 0;
string a;
getline(cin,a);
a=a+' ';
for(int i=0;i<a.size();i++){
int so=0,d=0;
if(a[i]>='0' && a[i]<='9'){
so=so+a[i]-48;
i++;
while(a[i]>='0' && a[i]<='9'){
so=so*10+a[i]-48;
i++;
}
tong += so;
}
}
cout<<tong;
return 0;
}
Cách 2:
#include <bits/stdc++.h>
#include <string.h>
#include <iostream>
using namespace std;
int convert(int c)
{
if(c == 48)
return 0;
if(c == 49)
return 1;
if(c == 50)
return 2;
if(c == 51)
return 3;
if(c == 52)
return 4;
if(c == 53)
return 5;
if(c == 54)
return 6;
if(c == 55)
return 7;
if(c == 56)
return 8;
if(c == 57)
return 9;
}
long long convert_number(int a[],int n)
{
long long sum = 0 , k = n - 1;
for(int i = 0 ; i < n ; i++)
{
sum = sum + a[i]*pow(10,k);
k--;
}
return sum;
}
int main()
{
char *s = new char[501];
gets(s);
int x = 0 , b[100000], c[100000] , count = 0, t = 0, k , j = 0;
for(int i = 0 ; i < strlen(s) ; i++)
{
if(*(s+i) == '.' || *(s+i) == ',' || *(s+i) == ':' || *(s+i) == ' ')
{
if(t >= 1)
{
k = convert_number(c,j);
b[x++] = k;
j = 0;
count = 0;
}
}
if(*(s+i) >= 'a' && *(s+i) < 'z' || *(s+i) >= 'A' && *(s+i) <= 'Z' || *(s+i) >= '0' && *(s+i) <= '9')
{
count++;
if(*(s+i) >= '0' && *(s+i) <= '9')
c[j++] = convert((int)*(s+i));
if(count == 1)
t++;
}
}
if(*(s+strlen(s)-1) != ',' , *(s+strlen(s)-1) != ':' , *(s+strlen(s)-1) != ':' , *(s+strlen(s)-1) != ' ')
{
int f = convert_number(c,j);
b[x++] = f;
}
long long sum = 0;
for(int i = 0 ; i < x ; i++)
sum += b[i];
cout<<sum;
return 0;
}