iT邦幫忙

2022 iThome 鐵人賽

DAY 9
0
自我挑戰組

Udemy課程上完你也可以開始Codewars 30天系列 第 9

[Day9] Codewars >>> Playing with digits (Python)

  • 分享至 

  • xImage
  •  

題目(6kyu):

DESCRIPTION:
Some numbers have funny properties. For example:

89 --> 8¹ + 9² = 89 * 1
695 --> 6² + 9³ + 5⁴= 1390 = 695 * 2
46288 --> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51

Given a positive integer n written as abcd... (a, b, c, d... being digits) and a >positive integer p

we want to find a positive integer k, if it exists, such that the sum of the digits of >n taken to the successive powers of p is equal to k * n.
In other words:
Is there an integer k such as : (a ^ p + b ^ (p+1) + c ^(p+2) + d ^ (p+3) + ...) = n * k

If it is the case we will return k, if not return -1.

Note: n and p will always be given as strictly positive integers.

解題思路

題目理解:給定一個正整數n以及n,先將n其每個位數拆分(Ex:abcd...)。
再依序將a^p,b^(p+1),c^(p+2),d^(p+d)...相加得到一個總和,若此總和乘上某正整數k恰可以等於n本身,則函式返還k,否則返還-1。

def dig_pow(n, p):
    num_lst = [ i for i in str(n) ] #先將數字照原順序拆分成列表儲存
    sum = 0
    pow = p
    for i in range(len(num_lst)): #逐一計算每個位數的次方和
        sum += int(num_lst[i])**pow
        pow +=1
    if sum % n == 0: #若能sum能被n整除,代表存在正整數k
        return int(sum/n) #故返還k = sum/n
    return -1

上一篇
[Day8] Codewars >>> Build a pile of Cubes (Python)
下一篇
[Day10] Codewars >>> Maximum subarray sum (Python)
系列文
Udemy課程上完你也可以開始Codewars 30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言