CodeWars: highest and lowest

codewars

這幾天遇到程式的面試題目,想說也可以一併將解法分享٩(^ᴗ^)۶
題目:Codewars - Highest and Lowest
一樣會用RubyPythonJavaScript三個語言來解題,讓我們開始吧!

Ruby

1
2
3
def high_and_low(numbers)
numbers.split.map(&:to_i).minmax.reverse.join(' ')
end

Ruby有一個蠻好用的方法,Array#minmax,可以回傳陣列的最小值和最大值,範例如下:

1
[0, 1, 2].minmax # => [0, 2]

但題目是high_and_low,所以需要reverse,並使用.join(' ')將陣列轉為字串。

Python

1
2
3
def high_and_low(numbers):
numbers = list(map(int, numbers.split()))
return f"{max(numbers)} {min(numbers)}"

f"{max(numbers)} {min(numbers)}"這裡使用f-string將最大值和最小值插入到字符串中

JavaScript

1
2
3
4
function highAndLow(numbers) {
const nums = numbers.split(' ').map(Number);
return `${Math.max(...nums)} ${Math.min(...nums)}`;
}

JS和Python也是用類似方法~

Comments