這一題的思路還是比較清晰的:
首先,由於每個數都是50位,還要計算100個這樣的數的和,unsigned long long 都表示不了這麼大的數,硬上肯定是不行滴;
那麼,考慮到只需要列印出和值的頭10位,才有了用多維陣列求解的方法:
1. 首先把這100個數字儲存到text檔案中:這樣比較好讀取。
2. 把這個檔案中的所有數字解析到arr[100][50]中。
3. 從最後一列開始計算一列的和,個位元(%10)進棧,剩下的(/10)作為下一列求和的進位元(基數)。每一列都這麼算,直到j=0最後一列:需要把sumColumn逐位分解進棧。
4. 好,現在stack中從上到下存的就是100個數的和了。pop出top 10,就是需要的前10位元。
View Code #include "stdafx.h"
#include <stack>
#include <fstream>
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
// read the num array from a txt file.
int arr[100][50];
ifstream numFile("d:\\problem13.txt");
char strNumLine[51];
int i = 0;
while(numFile.getline(strNumLine, 51))
{
int j = 0;
while(j < 50)
{
arr[i][j] = strNumLine[j] - '0';
j++;
}
i++;
}
// define a stack. kick off the sum of every column and push the last number of the sum into stack.
stack<int> numStack;
int sumColumn = 0;
for(int j = 49; j >= 0; j--)
{
for(int i = 0; i <= 99; i++)
{
sumColumn += arr[i][j];
}
if(j != 0)
{
numStack.push(sumColumn%10);
sumColumn = sumColumn / 10;
}
else
{
while(sumColumn > 1)
{
numStack.push(sumColumn%10);
sumColumn /= 10;
}
}
}
// pop up the last ten number in stack. They are the top ten number of the whole sum.
i = 1;
while(i <= 10)
{
cout << numStack.top() << endl;
numStack.pop();
i++;
}
return 0;
}