๐ 1. ๋ฌธ์
[Codewars, 6kyu] Playing with digits
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 as 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.
digPow(89, 1) should return 1 since 8ยน + 9ยฒ = 89 = 89 * 1
digPow(92, 1) should return -1 since there is no k such as 9ยน + 2ยฒ equals 92 * k
digPow(695, 2) should return 2 since 6ยฒ + 9ยณ + 5โด= 1390 = 695 * 2
digPow(46288, 3) should return 51 since 4ยณ + 6โด+ 2โต + 8โถ + 8โท = 2360688 = 46288 * 51
โ ํ์ด
function digPow(n, p) {
let result = 0;
let arr = n.toString().split("");
for (let i = 0; i < arr.length; i++) {
result = Math.pow(arr[i], p + i) + result;
}
return result % n ? -1 : result / n;
}
Math.pow
๋ก ์ ๊ณฑ๊ทผ ๊ณ์ฐ์ ํ๋ค.**
์ฐ์ฐ์๋ ๊ฐ๋ฅ..! ์ผํญ์ฐ์ฐ์ ์ฌ์ฉํด์ ์ฝ๋ ๊ธธ์ด๋ฅผ ์ตธํผ..์ค์์ง๋ง ๋ค์๋ถํฐ๋result = Math.pow(arr[i], p + i) + result;
๋์result += Math.pow(arr[i], p + i);
์ฌ์ฉํ ๊ฒ..
๐ 2. ๋ฌธ์
[Codewars, 7kyu] Number of People in the Bus
There is a bus moving in the city, and it takes and drop some people in each bus stop.
You are provided with a list (or array) of integer arrays (or tuples). Each integer array has two items which represent number of people get into bus (The first item) and number of people get off the bus (The second item) in a bus stop.
Your task is to return number of people who are still in the bus after the last bus station (after the last array). Even though it is the last bus stop, the bus is not empty and some people are still in the bus, and they are probably sleeping there :D
Take a look on the test cases.
Please keep in mind that the test cases ensure that the number of people in the bus is always >= 0. So the return integer canโt be negative.
The second value in the first integer array is 0, since the bus is empty in the first bus stop.
Test.assertEquals(number([[10,0],[3,5],[5,8]]),5);
Test.assertEquals(number([[3,0],[9,1],[4,10],[12,2],[6,1],[7,10]]),17);
Test.assertEquals(number([[3,0],[9,1],[4,8],[12,2],[6,1],[7,8]]),21);
โ ํ์ด
var number = function (busStops) {
let a = 0;
busStops.forEach((arr) => {
a = arr[0] - arr[1] + a;
});
return a;
};
๐ Best
const number = (busStops) =>
busStops.reduce((rem, [on, off]) => rem + on - off, 0);
- ๋ด ํ์ด๋ณด๊ณ best ํ์ด๋ณด๋๊น ํจ์ฌ ๊น๋.. ๋ชจ๋ ์์ ์ ๋ถ ๋ํ ๋๋
forEach
๋ง๊ณreduce
ํจ์ ์ฌ์ฉํ์..