高中生程式解題系統:阿姆斯壯數 Armstrong number

若您覺得文章寫得不錯,請點選文章上的廣告,來支持小編,謝謝。

題目連結 http://zerojudge.tw/ShowProblem?problemid=a040。可與 Python 阿姆斯壯數 一文對照。

C++ 的版本先建立好阿姆斯壯數的對應表,這個阿姆斯壯數可以從 Google 找到,而筆者是用程式跑出來的。

底下是Python版本所用的方法:
首先要知道數字是幾位數,可將數字轉成字串後,在呼叫計算字串長度函數 order = len(str(x)) ,接著就是將每位數的 order 次方加總(s),並檢查是否與原來數字相等
程式碼:

#include <iostream>
using namespace std;
int main()
{
int armstrongNum[] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
153, 370, 371, 407,
1634, 8208, 9474,
54748, 92727, 93084,
548834
};
short SIZE = sizeof(armstrongNum) / sizeof(int);
bool isArmstrong[1000000];
for(int i = 0; i < SIZE; i++)
isArmstrong[armstrongNum[i]] = true;
int a, b;
while(cin >> a >> b)
{
bool hasArm = false;
for( ; a <= b; a++ )
{
if(isArmstrong[a])
{
cout << a << " ";
hasArm = true;
}
}
if(!hasArm)
cout << "none";
cout << endl;
}
return 0;
}
view raw a040.cpp hosted with ❤ by GitHub

沒有留言: