python笔记之水仙花数

水仙花数(Narcissistic number)也被称为超完全数字不变数(pluperfect digital invariant, PPDI)、自恋数、自幂数、阿姆斯壮数或阿姆斯特朗数(Armstrong number),水仙花数是指一个 n 位数(n≥3 ),它的每个位上的数字的 n 次幂之和等于它本身(例如:1^3 + 5^3+ 3^3 = 153)。

问题:

编写一个程序,求100~999之间的所有水仙花数:

答案1(对数字进行处理):

for i in range(100, 1000):
    sum = 0
    temp = i
    while temp:
        sum = sum + (temp%10) ** 3
        temp //= 10         # 注意要使用地板除!
    if sum == i:
        print(i)
View Code

答案2(对数字作为字符串处理):

for i in range(100, 1000):
    string = str(i)
    length = len(string)
    temp = 0
    for j in range(length):
        temp += int(string[j]) ** 3
    if temp == i:
        print(i)
View Code
原文地址:https://www.cnblogs.com/lanhoo/p/7688331.html