001: 水仙花数(阿姆斯特朗数)

时间:2022-11-19 17:56:45

假设存在一个k位数 N,其每一位上的数字的 k次幂 的总和也是 N,那么这个数是阿姆斯特朗数。
给你一个正整数N,判断是否是阿姆斯特朗数,若是,返回True,否则,返回False
举例:
153是一个3位数,且153 = 1^3 + 5^3 +3^3

链接:https://leetcode-cn.com/problems/armstrong-number

有5种方法,如下:

def test1(N):
	tmp = N
	list = []
	while tmp / 10 > 0:
		s = tmp % 10
		list.append(s)
		tmp = tmp // 10

	sum = 0
	for item in list:
		sum += item ** len(list)

	return sum == N

res = test1(153)
print(res)
def test2(N):
	strN = str(N)
	list = []
	sum = 0
	for item in strN:
		list.append(item)
	for item in list:
		sum += int(item) ** len(list)
	return sum == N

res = test2(153)
print(res)
def test3(N):
	strN = str(N)
	list = [item for item in strN]
	sum = 0
	for item in list:
		sum += int(item) ** len(list)
	return sum == N

res = test3(153)
print(res)
def test4(N):
	lis = list(str(N))
	sum = 0
	for i in range(len(lis)):
		sum += int(lis[i]) ** len(lis)
	return sum == N

res = test4(153)
print(res)
def test5(N):
	lis = list(str(N))
	sum = 0
	for item in lis:
		sum += int(item) ** len(lis)
	return sum == N

res = test5(153)
print(res)