PTA 7-148 判断一个三位数是否为水仙花数

PTA 7-148 判断一个三位数是否为水仙花数


题目描述:

本题要求编写程序,判断一个给定的三位数是否为水仙花数。三位水仙花数,即其个位、十位、百位数字的立方和等于该数本身。

输入格式:

输入在一行中给出一个需要判断的整数 N(100≤N≤999)。

输出格式:

如果N是水仙花数,则在一行中输出Yes,否则输出No。如果N不是三位数,则输出Invalid Value.

输入样例1:

153

输出样例1:

Yes

输入样例2:

500

输出样例2:

No

输入样例3:

-2

输出样例3:

Invalid Value.

思路:

只需要知道一个结论即可:

在所有整数里面水仙花数有且只有4个:153、370、371、407.

类似题目见: PTA 7-151 找出三位水仙花数


常规代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

int main()
{
    int n;
    cin >> n;
    
    int sum = n;
    int a = n % 10; a = a * a * a;
    n /= 10;
    int b = n % 10; b = b * b * b;
    n /= 10;
    int c = n; c = c * c * c;
    
    if (sum < 100 || sum > 999){
        cout << "Invalid Value." << endl;
        return 0;
    }
    else if (a + b + c == sum)
        cout << "Yes" << endl;
    else cout << "No" << endl;
    
    return 0;
}

小巧代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

int main()
{
    int n;
    cin >> n;
 
    if (n < 100 || n > 999){
        cout << "Invalid Value." << endl;
        return 0;
    }
    
    if (n == 153 || n == 370 || n == 371 || n == 407)
        cout << "Yes" << endl;
    else cout << "No" << endl;
    
    return 0;
}

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BraumAce

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值