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; 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"); +});