Skip to content

Commit 669a20c

Browse files
committed
Create 017.js
1 parent ac3f1c7 commit 669a20c

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

017.js

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
//function that takes a natural number n between 1 and 1000 as input and returns a string of its "word form"
2+
function numberToWord(n) {
3+
//listing out 1-19 in an array such that numbers[n] will return n in word form
4+
const numbers = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"];
5+
const numbersTimes10 = [null, null, "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"];
6+
7+
if (n < 20) {
8+
return numbers[n];
9+
} else if (n < 100) {
10+
let wordForm = "";
11+
12+
let tens = Math.floor(n / 10);
13+
let ones = n - (10 * tens);
14+
15+
wordForm += numbersTimes10[tens];
16+
17+
if (ones > 0) {
18+
wordForm += "-"; //adding a hyphen between tens and ones because that's how they do it on the problem page (we remove the hyphen later when finding the length of the word tho so idk why i added this)
19+
wordForm += numbers[ones];
20+
}
21+
22+
return wordForm;
23+
} else if (n < 1000) {
24+
let wordForm = "";
25+
26+
let hundreds = Math.floor(n / 100);
27+
let restOfTheNumber = n - (100 * hundreds);
28+
29+
wordForm += `${numbers[hundreds]} hundred`;
30+
31+
if (restOfTheNumber > 0) {
32+
wordForm += " and ";
33+
wordForm += numberToWord(restOfTheNumber); //we love recursion
34+
}
35+
36+
return wordForm;
37+
} else {
38+
return "one thousand";
39+
}
40+
}
41+
42+
// "Do not count spaces or hyphens."
43+
function length(wordFormString) {
44+
wordFormString = wordFormString.split(" ").join(""); //gets rid of spaces
45+
wordFormString = wordFormString.split("-").join(""); //gets rid of hyphens
46+
47+
return wordFormString.length;
48+
}
49+
50+
let sum = 0; // accumulator variable
51+
52+
for (let i = 1; i <= 1000; i++) {
53+
sum += length(numberToWord(i));
54+
}
55+
56+
console.log(sum); // the answer!

0 commit comments

Comments
 (0)