Practice
At one time a popular interview task was “Write a function that converts a number into its text representation”; here is one of the possible solutions to this task:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
|
/*!
*
* Function numToWord() for converting
* nubmer from numeric to text representation
*
* Copyright 2013 Roman Gushel
*/
// Array of degrees spellings
var assocArr = [];
assocArr[0] = new Array("", "один", "два", "три", "четыри", "пять", "шесть", "семь","восемь", "девять");
assocArr["d"] = new Array("десять", "одинадцать", "двенадцать", "тринадцать", "четырнадцать","пятнадцать", "шеснадцать", "семнадцать", "восемнадцать", "девятнадцать");
assocArr[1] = new Array("", "", "двадцать", "тридцать", "сорок", "пятьдесят", "шестьдесят","семьдесят", "восемьдесят", "девяносто");
assocArr[2] = new Array("", "сто", "двести", "триста", "четыреста", "пятьсот", "шестьсот","семьсот", "восемьсот", "девятьсот");
assocArr["s"] = new Array("", "одна", "две");
assocArr[3] = new Array("тысяч", "тысяча", "тысячи", "тысячи", "тысячи", "тысяч", "тысяч","тысяч", "тысяч", "тысяч", "");
/*
* Converting
* nubmer from numeric to text representation
*
* @param {number} number for conversion
* @return {text} converted string
*
*/
function numToWord(number) {
var resp = "",
numArr = [],
flag = true;
// Checking the input conditions
if (isNaN(number) || number < 1 || number > 9999) {
return "Invalid input!";
}
// Convert input number to array of digits
for (; number != 0; number = Math.floor(number / 10)) {
numArr.push(number % 10);
}
// Iterate all digits from the end
for (var i = numArr.length - 1; i >= 0 ; i--) {
if (flag) {
if (numArr[i] == 1 && i == 1 || numArr[i] == 1 && i == 4) {
flag = false;
} else {
resp += digitToWord(i, numArr[i], 0);
}
} else {
resp += digitToWord("d", numArr[i], i);
flag = true;
}
}
return resp.trim();
}
function digitToWord(digit, offset, char) {
var resp = "";
switch (digit) {
case 3:
resp += (offset == 1 || offset == 2 ? assocArr["s"][offset] : assocArr[0][offset]) + " ";
break;
case 4:
digit = 1;
break;
case "d":
resp += assocArr[digit][offset] + " ";
digit = char;
offset = 0;
break;
}
return resp + assocArr[digit][offset] + " ";
}
|
Comments