-
Notifications
You must be signed in to change notification settings - Fork 0
/
P4.js
71 lines (55 loc) · 1.62 KB
/
P4.js
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
/* ====== Problem 1 =================================== *
*
* A palindromic number reads the same both ways. The largest
* palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
*
* Find the largest palindrome made from the product of two 3-digit numbers.
*
* ========================================**/
function getFirst(str) {
return str.substr(0, 1);
}
function getLast(str) {
return str.substr(-1, str.length - 1);
}
function getMiddle(str) {
return str.slice(1, -1);
}
function isPalindrome(x) {
if (x.length === 1 || x.length === 0)
return true;
if (getFirst(x) === getLast(x)) {
return isPalindrome(getMiddle(x));
}
return false;
}
function getProductOfPalindrome(base, max) {
var palindromeProduct = [];
for (var i = base; i < max; i++) {
for (var j = base; j < max; j++) {
product = i * j;
if (isPalindrome(product.toString()))
palindromeProduct.push(product);
}
}
return Math.max.apply(Math, palindromeProduct);
}
function solution(data) {
var base = Math.pow(10, data.digitLimit - 1);
var max = Math.pow(10, data.digitLimit);
var answer = getProductOfPalindrome(base, max);
console.log(`The largest palindrome made from 3-digit numbers is: ${answer}`);
}
solution({
digitLimit: 3
});
/* ====== Meta ========================================= *
*
* Estimated time of completion: 40 minutes
* Search engine used: Yes
* Concepts learned: Math.max.apply() / analogously Math.min.apply();
* Math.pow(base, exponent);
*
* Additional notes: Beginning to get a bit better at
*
* ========================================**/