iT邦幫忙

2022 iThome 鐵人賽

DAY 8
0
自我挑戰組

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

[Day8] Codewars >>> Build a pile of Cubes (Python)

  • 分享至 

  • xImage
  •  

題目(6kyu):

Your task is to construct a building which will be a pile of n cubes. The cube at the >bottom will have a volume of n^3, the cube above will have volume of (n-1)^3 and so on >until the top which will have a volume of 1^3.

You are given the total volume m of the building. Being given m can you find the number >n of cubes you will have to build?
The parameter of the function findNb (find_nb, find-b, findNb, ...) will be an integer >m and you have to return the integer n such as n^3 + (n-1)^3 + ... + 1^3 = m if such a >n exists or -1 if there is no such n.

Examples:
findNb(1071225) --> 45

findNb(91716553919377) --> -1

解題思路

題目理解:假底一立方體組成之建築物,最底下立方體體積為n^3;則再往上一層的立方體體積為(n-1)^3,以此類推直到最頂部立方體體積為1^3為止。給定一個建築物總體積m,返還建造此建築物所需的立方體數量n,若找不到此數字n則返還-1。

def find_nb(m):
    #先假定n等於1從最上層開始計算總建築物體積
    n = 1
    building_volume = 0
    #持續往下層累加體積,若累計體積超出m代表找不到符合的立方體數量
    while building_volume <= m:
        building_volume += n**3
        #若累積體積洽等於m,此時n則剛好是目標需要的立方體個數
        if building_volume == m:
            return n
        n += 1
    return -1

上一篇
[Day7] Codewars >>> Number of trailing zeros of N!(Python)
下一篇
[Day9] Codewars >>> Playing with digits (Python)
系列文
Udemy課程上完你也可以開始Codewars 30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言