切換
舊版
前往
大廳
主題

[創作|作業][C++]演算法Week1:1-happy number

極巨龍神塔奇 | 2018-03-23 20:32:11 | 巴幣 6 | 人氣 1307

快樂數
若將一個整數 n 的所有數字拆開分別平方後再相加,如此反覆進行至只剩個位數之後,其結果為 1 ,則我們稱 n 為快樂數。
例如
32 → 3 ^ 2 + 2 ^ 2 = 13
13 → 1 ^ 2 + 3 ^ 2 = 10
10 → 1 ^ 2 + 0 ^ 2 = 1
可以稱32為快樂數。
Input的第一個數字為測資個數;Output為Happy或Not Happy。
範例輸入:
2
32
87
範例輸出:
Happy
Not Happy


/*----- ----- ----- -----*/
//1-happy number
//Made by 105502555 Teemo Hsu(Synasaivaltos)
//Date: 2018/03/15
/*----- ----- ----- -----*/
#include <iostream>
#include <vector>

using namespace std;

int square(int x)
{
   return x*x;
}

int main(void)
{
   int n;
   cin >> n;
   vector<bool> ans;

   while(--n>=0)
   {
      int a;
      cin >> a;
      while(a>9)
      {
         int sum=0;
         while(a!=0)
         {
            sum+=square(a%10);
            a/=10;
         }
         a=sum;
      }
      ans.push_back((a==1)?true:false);
   }

   for(int i=0;i<ans.size();cout<<((ans.at(i)==true)?"Happy\n":"Not Happy\n"),i++);

   return 0;
}
送禮物贊助創作者 !
0
留言

創作回應

嗡嗡
覺得快樂((廢話
2018-03-23 21:01:56
嗡嗡
/*----- ----- ----- -----*/
//1-happy number
//Made by Tony_Won
//Date: 2018/03/23
/*----- ----- ----- -----*/
#include<iostream>
using namespace std;
int main(){
int count;
cin>>count;
for(int i=0;i<count;i++){
int num;
cin>>num;
while(num>9){
int sum=0;
while(num!=0){
sum+=(num%10)*(num%10);
num/=10;
}
num=sum;
}
if(num==1) cout<<"Happy"<<endl;
else cout<<"Not Happy"<<endl;
}
return 0;
}
2018-03-23 21:20:07
極巨龍神塔奇
要全部測資輸入完才能cout
2018-03-23 23:48:57
極巨龍神塔奇
看錯題目要求直接0分
2018-03-24 00:10:56

更多創作