ISSUE
In this kata we want to convert a string into an integer. The strings simply represent the numbers in words.
Examples:
"one" => 1 "twenty" => 20 "two hundred forty-six" => 246 "seven hundred eighty-three thousand nine hundred and nineteen" => 783919 Additional Notes:
The minimum number is "zero" (inclusively) The maximum number, which must be supported is 1 million (inclusively) The "and" in e.g. "one hundred and twenty-four" is optional, in some cases it's present and in others it's not All tested numbers are valid, you don't need to validate them
describe("Tests", () => {
it("test", () => {
Test.assertEquals(parseInt('one'), 1);
Test.assertEquals(parseInt('twenty'), 20);
Test.assertEquals(parseInt('two hundred forty-six'), 246);
});
});
翻译
在这个kata中,我们想把一个字符串转换成一个整数。字符串只是用文字表示数字。 例如: “one”=>1 twenty=>20 two hundred forty-six=>246 “seven hundred eighty-three thousand nine hundred and nineteen”=>783919 补充说明: 最小数字为“0”(含) 必须支持的最大数量为100万(含) 例如“124”中的“and”是可选的,在某些情况下是存在的,而在另一些情况下不是 所有测试的数字都是有效的,你不需要验证它们
前奏
- 好家伙,这题是要做洋数字“翻译官”
solution
/**
- @author zowie
- @param {string} string
- @return {number} */
let ONES = {
"negative": -1, "zero": 0, "one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10, "eleven": 11, "twelve": 12, "thirteen": 13, "fourteen": 14, "fifteen": 15, "sixteen": 16, "seventeen": 17, "eighteen": 18, "nineteen": 19
}
let TENS = { "twenty": 20, "thirty": 30, "forty": 40, "fifty": 50, "sixty": 60, "seventy": 70, "eighty": 80, "ninety": 90 }
// , "hundred": 100, "thousand": 1000, "million": 1000000
function parseInt(string) {
let number = []
strs = string.split(' and ').join(' ').split('-').join(' ').split(' ')
for (token of strs) {
if (token in ONES) {
number.push(ONES[token])
} else if (token in TENS) {
number.push(TENS[token])
} else if (token == 'hundred') {
number[number.length - 1] *= 100
} else if (token == 'thousand') {
for (item in number) { number[item] *= 1000 }
} else if (token == 'million') {
for (item in number) { number[item] *= 1000000 }
}
}
return eval(number.join('+'))
}
console.log(parseInt('seven hundred eighty-three thousand nine hundred and nineteen'))