- 哈沙德数
如果一个整数能够被其各个数位上的数字之和整除,则称之为 哈沙德数(Harshad number)。给你一个整数 x 如果 x 是 哈沙德数 ,则返回 x 各个数位上的数字之和,否则,返回 -1 。
示例 1:
输入: x = 18
输出: 9
解释:
x 各个数位上的数字之和为 9 。18 能被 9 整除。因此 18 是哈沙德数,答案是 9 。
示例 2:
输入: x = 23
输出: -1
解释:
x 各个数位上的数字之和为 5 。23 不能被 5 整除。因此 23 不是哈沙德数,答案是 -1 。
提示:
10 <= x <= 100
# -- coding:utf-8 --num = 18def hashade(num):if num >= 100 and num < 10:print("num not in range")get_ten = num // 10get_ge = num % 10# print(get_ten, get_ge)sum = get_ten + get_ge# print(sum)if num % sum == 0:# print("right number")return sumelse:# print("err number")return -1if __name__ == '__main__':num = int(input("请输入10~100之间的数:"))res = hashade(num)print(res)
测试:
请输入1~100之间的数:99
-1请输入1~100之间的数:18
9请输入1~100之间的数:123
-1
10~100以内的哈沙德数:
# -- coding:utf-8 --num = 18def hashade(num):if num >= 100 and num < 10:print("num not in range")get_ten = num // 10get_ge = num % 10# print(get_ten, get_ge)sum = get_ten + get_ge# print(sum)if num % sum == 0:# print("right number")return sumelse:# print("err number")return -1def hashade_100(num):get_ten = num // 10get_ge = num % 10# print(get_ten, get_ge)sum = get_ten + get_ge# print(sum)if num % sum == 0:# print("right number")return sumelse:# print("err number")return -1if __name__ == '__main__':# num = int(input("请输入10~100之间的数:"))# res = hashade(num)res_list = []for num in range(10, 100):res = hashade_100(num)if res != -1:res_list.append([num, res])print("num :", num, " res:", res)print(res_list)
log
num : 10 res: 1
num : 12 res: 3
num : 18 res: 9
num : 20 res: 2
num : 21 res: 3
num : 24 res: 6
num : 27 res: 9
num : 30 res: 3
num : 36 res: 9
num : 40 res: 4
num : 42 res: 6
num : 45 res: 9
num : 48 res: 12
num : 50 res: 5
num : 54 res: 9
num : 60 res: 6
num : 63 res: 9
num : 70 res: 7
num : 72 res: 9
num : 80 res: 8
num : 81 res: 9
num : 84 res: 12
num : 90 res: 9
[[10, 1], [12, 3], [18, 9], [20, 2], [21, 3], [24, 6], [27, 9], [30, 3], [36, 9], [40, 4], [42, 6], [45, 9], [48, 12], [50, 5], [54, 9], [60, 6], [63, 9], [70, 7], [72, 9], [80, 8], [81, 9], [84, 12], [90, 9]]