CodeWars : 新手村练等纪录02- Growth of a Population

Growth of a Population

等级:7kyu

原始题目

In a small town the population is p0 = 1000 at the beginning of a year. The population regularly increases by 2 percent per year and moreover 50 new inhabitants per year come to live in the town. How many years does the town need to see its population greater or equal to p = 1200 inhabitants?

At the end of the first year there will be: 1000 + 1000 * 0.02 + 50 => 1070 inhabitantsAt the end of the 2nd year there will be: 1070 + 1070 * 0.02 + 50 => 1141 inhabitants (** number of inhabitants is an integer **)At the end of the 3rd year there will be:1141 + 1141 * 0.02 + 50 => 1213It will need 3 entire years.

More generally given parameters:
*p0*, *percent*, *aug*(inhabitants coming or leaving each year), *p* (population to surpass)

the functionnb_yearshould return n number of entire years needed to get a population greater or equal to p.
aug is an integer, percent a positive or null floating number, p0 and p are positive integers (> 0)

Note:
Don't forget to convert the percent parameter as a percentage in the body of your function: if the parameter percent is 2 you have to convert it to 0.02.

Examples:nb_year(1500, 5, 100, 5000) -> 15nb_year(1500000, 2.5, 10000, 2000000) -> 10

中翻:
nb_year这个function要能回传人口成长到一定数量所需的时间(单位:年)
参数共有4个

p0:代表原始人口percent:表示成长数值(需要另外换算成百分比)aug:表示每年新增/减少的人口,此数值可能为正整数或负整数p:为预计成长到的人口数量

自解:

export class G964 {    public static nbYear = (p0, percent, aug, p) => {           let inhabitants = p0;        let i = 0        while(inhabitants < p){          inhabitants = Math.floor((1 + percent/100)* inhabitants) + aug;          i++        }         return i    }}

这次题目算是比较单纯的在测试迴圈的撰写,我使用的是whlie的写法,另外有用Math.floor方法取整数(因为人口不会是小数点,但在此题应该是非必要的处理)

下方有其他人用for迴圈的写法可以参考。

他解:

author: g964

export class G964 {    public static nbYear = (p0, percent, aug, p) => {        for(var y = 0; p0 < p; y++) p0 = p0 * (1 + percent / 100) + aug;        return y;    }}

此次题目使用到的方法和参考网址:

Math.floor() 函式会回传小于等于所给数字的最大整数。
https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Math/floor

(另外补充)Math.celi() 函式会回传大于等于所给数字的最小整数。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/ceil

(另外补充)Static function 突然对static function的用法和意义有点模糊,看到此题刚好去複习一下
https://medium.com/enjoy-life-enjoy-coding/typescript-%E5%BE%9E-ts-%E9%96%8B%E5%A7%8B%E5%AD%B8%E7%BF%92%E7%89%A9%E4%BB%B6%E5%B0%8E%E5%90%91-class-%E7%94%A8%E6%B3%95-20ade3ce26b8
来源: 神Q超人
此篇也顺便複习整个class用法。


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章