From 43e2209909c357ba57db5a350868d697889b9a40 Mon Sep 17 00:00:00 2001 From: Hidemichi Shimura Date: Tue, 17 Jan 2023 07:58:17 -0800 Subject: [PATCH 1/2] solve 1556. Thousand Separator --- 1556.thousand-separator.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 1556.thousand-separator.js diff --git a/1556.thousand-separator.js b/1556.thousand-separator.js new file mode 100644 index 00000000..d7e6fda6 --- /dev/null +++ b/1556.thousand-separator.js @@ -0,0 +1,21 @@ +/* URL of this problem + * https://leetcode.com/problems/thousand-separator/description/ + * + * @param {number} n + * @return {string} + */ + +var thousandSeparator = function (n) { + let str = n.toString(); + const SeparatatedStr = []; + + // Extract the last 3 digits and add them to SeparatatedStr in an order by occurrence + while (str.length > 0) { + SeparatatedStr.unshift(str.substring(str.length - 3, str.length)); + str = str.substring(0, str.length - 3); + } + + return SeparatatedStr.join("."); +}; + +module.exports = thousandSeparator; From 9bfb98f2cc8aec0467c7238c5841eed9ff67c059 Mon Sep 17 00:00:00 2001 From: Hidemichi Shimura Date: Tue, 17 Jan 2023 07:58:39 -0800 Subject: [PATCH 2/2] test function thousandSeparator --- thousandSeparator.test.js | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 thousandSeparator.test.js diff --git a/thousandSeparator.test.js b/thousandSeparator.test.js new file mode 100644 index 00000000..dc9c24c9 --- /dev/null +++ b/thousandSeparator.test.js @@ -0,0 +1,13 @@ +const thousandSeparator = require("../jest-test/1556.thousand-separator"); + +test("Return a string wihtout any separator dot", () => { + expect(thousandSeparator(987)).toBe("987"); +}); + +test("Return a string seperated by dots", () => { + expect(thousandSeparator(1234)).toBe("1.234"); +}); + +test("Return a string of 0s seperated by dots if the input n consists only of 0", () => { + expect(thousandSeparator(0000000)).toBe("0.000.000"); +});