題目描述
求輸入的一個正整數的各位數字之和
輸入
一行一個整數
輸出
一個整數
樣例輸入 Copy
<code>2147483646/<code>
樣例輸出 Copy
<code>45/<code>
【算法分析】
對於單精度數,可以採用拆數的方法取得每一位直接累加(見程序一);對於大數據(比如整數大於21億)可以採用字符串來處理(程序二)。
<code>//程序一
#include <bits>
using namespace std;
int main()
{
\tint n,sum=0;
\tcin>>n;
\tfor(int i=1;n>0;i++)
\t{
\t\tsum=sum+n%10;//利用n%10循環取得每一位數字
\t\tn=n/10;
\t}
\tcout<\treturn 0; /<bits>/<code>
}
////程序二
#include <bits>
using namespace std;
int main()
{
\tstring s;
\tcin>>s;
\tint sum=0;
\tfor(int i=0;i<s.size> \t{
\t\tsum+=(s[i]-'0');\t//s[i]-'0'即為每一位數字
\t}
\tcout<\treturn 0; /<s.size>/<bits>
}
![c++刷題基礎篇:各位數字之和](http://p2.ttnews.xyz/loading.gif)
程序一運行結果,適用單精度數
![c++刷題基礎篇:各位數字之和](http://p2.ttnews.xyz/loading.gif)
程序二運行結果,測試數據超出程序一數據範圍,只使用程序二
閱讀更多 機房日子 的文章