add: 整数转罗马数字
This commit is contained in:
parent
6036e99c52
commit
1cacc57721
1
.vscode/settings.json
vendored
1
.vscode/settings.json
vendored
@ -1,5 +1,6 @@
|
|||||||
{
|
{
|
||||||
"cSpell.words": [
|
"cSpell.words": [
|
||||||
|
"LVIII",
|
||||||
"abcdefg",
|
"abcdefg",
|
||||||
"cdefgab",
|
"cdefgab",
|
||||||
"chuan",
|
"chuan",
|
||||||
|
19
src/string/integer-to-roman.js
Normal file
19
src/string/integer-to-roman.js
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
/**
|
||||||
|
* @param {number} num
|
||||||
|
* @return {string}
|
||||||
|
*/
|
||||||
|
export const intToRoman = function (num) {
|
||||||
|
const nums = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
|
||||||
|
const chars = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']
|
||||||
|
let result = ''
|
||||||
|
while (num) {
|
||||||
|
if (num >= nums[0]) { // 3 > 1 => 2 > 1 => 1 == 1
|
||||||
|
result += chars[0] // I => II => III
|
||||||
|
num -= nums[0] // 3 -> 2 => 2 -> 1 => 1 => 0
|
||||||
|
} else {
|
||||||
|
nums.shift()
|
||||||
|
chars.shift()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
9
test/string/integer-to-roman.test.js
Normal file
9
test/string/integer-to-roman.test.js
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
import { intToRoman } from '../../src/string/integer-to-roman'
|
||||||
|
|
||||||
|
test('整数转罗马数字', () => {
|
||||||
|
expect(intToRoman(2)).toBe('II')
|
||||||
|
expect(intToRoman(3)).toBe('III')
|
||||||
|
expect(intToRoman(4)).toBe('IV')
|
||||||
|
expect(intToRoman(9)).toBe('IX')
|
||||||
|
expect(intToRoman(58)).toBe('LVIII')
|
||||||
|
})
|
Loading…
Reference in New Issue
Block a user