APCS程式檢測 -實作題1060304 第1題 秘密差



乍看會覺得用數字 int 就可以解決,但是看到後面的測試位數會有「不超過 1000 位」,那最多還是會有 999 個位數啊,不只 int 無法處理,連 long long 也無法處理,所以這題必須要用字串。
這段如果看不懂,請看這篇-C++ -資料型態整理
https://husking-studio.com/cpp-datatype/
第一步:把字串轉成數字陣列

根據以下的 ascii code 表,會發現 字元的 ascii code 和 數字 差了 48,所以只要把字元轉成 ascii code 之後再減掉 48 就能變成數字了。

#include <iostream>
#include <string>
using namespace std;
int main()
{
string str("263541");
cout << "str[0] 字元 = " << str[0] << endl;
cout << "str[0] 字元 的 ascii code = " << (int)str[0] << endl;
int n = (int)str[0] - 48;
cout << "n = " << n << endl;
system("pause");
return 0;
}

完整程式碼
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
//處理輸入
string strX;
getline(cin, strX);
int strLen = strX.length();
//將 string 裡的資料轉換成數字陣列
int* array = new int[strLen];
for (int i = 0; i < strLen; i++)
{
array[i] = (int)strX[i] - 48;
}
//奇數位數的和
int nNumA = 0;
for (int i = 1; i < strLen; i = i + 2)
{
nNumA = nNumA + array[i];
}
//偶數位數的和
int nNumB = 0;
for (int i = 0; i < strLen; i = i + 2)
{
nNumB = nNumB + array[i];
}
//算出秘密差
int nY = abs(nNumA - nNumB);
//印出答案
cout << nY << endl;
delete[] array;
system("pause");
return 0;
}

