两种解法:
1、逐位相加
#include <iostream> #include <string> using namespace std; int main() { int s; cin>>s; int sum=0; while (s!=0) { sum=sum+s%10; s=s/10; } cout<<sum; return 0; }
2、转换成字符串相加
#include <iostream> #include <string> using namespace std; int main() { string s; cin>>s; int sum=0; for (int i=0;i<s.size();i++) { if (s[i]>='0'&& s[i]<='9') { int tmp; tmp=s[i]-'0'; sum=sum+tmp; } } cout<<sum; return 0; }
原文地址:http://blog.csdn.net/wtyvhreal/article/details/42442169