介紹
接著上次的中級算法題
目錄
- 1. Missing letters
- 2. Boo who
- 3. Sorted Union
- 4. Convert HTML Entities
- 5. Spinal Tap Case
- 6. Sum All Odd Fibonacci Numbers
- 7. Sum All Primes
1. Missing letters
Find the missing letter in the passed letter range and return it.
If all letters are present in the range, return undefined.
Here are some helpful links:
- String.prototype.charCodeAt()
- String.fromCharCode()
charCodeAt()
方法返回一個字符的UTF-16。
fromCharCode()
方法返回給定參數(shù)對應(yīng)的字符串,如有多個參數(shù),就用,
隔開。
思路
對比相鄰的兩字符,判斷他們的UTF-16差值是否等于1.
不等于1時,使用
fromCarCode()
方法返回較小值+1對應(yīng)的字符串。
function fearNotLetter(str) {
for (let i = 0, len = str.length; i < len - 1; i++) {
if (str.charCodeAt(i + 1) - str.charCodeAt(i) !== 1) {
return String.fromCharCode(str.charCodeAt(i) + 1);
}
}
return undefined;
}
2. Boo who
Check if a value is classified as a boolean primitive. Return true or false.
Boolean primitives are true and false.
Here are some helpful links:
- Boolean Objects
方法 1
直接用typeof即可
function booWho(bool) {
return typeof bool === 'boolean';
}
方法 2
Boolean函數(shù)
返回一個值為true或false的值,可利用這個特性進(jìn)行判斷。
function booWho(bool) {
return bool === Boolean(bool);
}
3. Sorted Union
Write a function that takes two or more arrays and returns a new array of unique values in the order of the original provided arrays.
In other words, all values present from all arrays should be included in their original order, but with no duplicates in the final array.
The unique numbers should be sorted by their original order, but the final array should not be sorted in numerical order.
Check the assertion tests for examples.
Here are some helpful links:
- Arguments object
- Array.prototype.reduce()
此題考察字符串去重
思路
利用
reduce()
方法和concat()
方法進(jìn)行數(shù)組的合并。利用
filter()
方法和indeof()
方法進(jìn)行去重。
function uniteUnique(arr) {
let arr1 = Array.prototype.slice.call(arguments);
arr1 = arr1.reduce((array1, array2) => {
return array1.concat(array2);
});
return arr1.filter((val, index) => {
return arr1.indexOf(val) === index;
});
}
4. Convert HTML Entities
Convert the characters &, <, >, " (double quote), and ' (apostrophe), in a string to their corresponding HTML entities.
Here are some helpful links:
- RegExp
- HTML Entities
- String.prototype.replace()
思路
確定正則表達(dá)式,/[&<>"']/g。
利用
replace()
方法和正則表達(dá)式替換掉對應(yīng)的字符即可。
function convertHTML(str) {
return str.replace(/[&<>"']/g, (val) => {
return '&' + {
'&': 'amp',
'<': 'lt',
'>': 'gt',
'"': 'quot',
'\'': 'apos'
}[val] + ';';
});
}
5. Spinal Tap Case
Convert a string to spinal case. Spinal case is all-lowercase-words-joined-by-dashes.
Here are some helpful links:
- RegExp
- String.prototype.replace()
思路
去掉
'_'
,替換成' '
(空格)。在所有大寫字母前加入一個空白。
如果開頭有空白,把空白去掉。
把大寫字母前的一個或多個空白換為'-'。
把大寫字母都轉(zhuǎn)為小寫。
function spinalCase(str) {
return str.replace(/_/g, ' ').replace(/([A-Z])/g, ' $1').replace(/^\s/, '').replace(/\s+/g, '-').toLowerCase();
}
6. Sum All Odd Fibonacci Numbers
Given a positive integer num, return the sum of all odd Fibonacci numbers that are less than or equal to num.
The first two numbers in the Fibonacci sequence are 1 and 1. Every additional number in the sequence is the sum of the two previous numbers. The first six numbers of the Fibonacci sequence are 1, 1, 2, 3, 5 and 8.
For example, sumFibs(10) should return 10 because all odd Fibonacci numbers less than 10 are 1, 1, 3, and 5.
Here are some helpful links:
- Remainder
菲波那切數(shù)列,從第三位起,每一位數(shù)都是前兩位數(shù)之和。此題求的是和,因此沒必要存儲數(shù)字,直接判斷后相加即可。
思路
判斷當(dāng)前的菲波那切數(shù)是否為奇數(shù),如果是,則加上
利用ES6的新語法解構(gòu)賦值,進(jìn)行簡單的數(shù)值交換。
function sumFibs(num) {
let a = 1;
let b = 1;
let sum = 0;
while (a <= num) {
sum += a % 2 !== 0 ? a : 0;
[a, b] = [b, a + b];
}
return sum;
}
7. Sum All Primes
Sum all the prime numbers up to and including the provided number.
A prime number is defined as a number greater than one and having only two divisors, one and itself. For example, 2 is a prime number because it's only divisible by one and two.
The provided number may not be a prime.
Here are some helpful links:
- For Loops
- Array.prototype.push()
質(zhì)數(shù),只能被1和其自身整除。利用各種質(zhì)數(shù)篩選法篩選好質(zhì)數(shù)后相加即可得到答案。
思路
利用某種質(zhì)數(shù)篩選法篩選出質(zhì)數(shù),并添加到數(shù)組里。
利用
reduce()
方法相加
方法 1
利用除法直接判斷。但這種算法重復(fù)率高,效率低。
function sumPrimes(num) {
if (num < 2) {
return 0;
}
let arr = [2];
let isPrime = 3;
while (isPrime <= num) {
// 判斷是否是質(zhì)數(shù)
for (let i = 0, len = arr.length; i < len; i++) {
if (isPrime % arr[i] === 0) {
break;
}
if (Math.pow(arr[i], 2) > isPrime) {
arr.push(isPrime);
break;
}
}
isPrime++;
}
return arr.reduce((sum, val) => {
return sum + val;
});
}
方法 2
利用埃拉托斯特里篩法進(jìn)行篩選。
ceil()
方法對一個浮點數(shù)向上取整。
function sumPrimes(num) {
let arr = [];
for (let i = 0; i <= num; i++) {
arr.push(i);
}
for (let i = 2, len = Math.ceil(Math.sqrt(num)); i < len; i++) {
if (!!arr[i]) {
for (let j = i * 2; j <= num; j += i) {
arr[j] = undefined;
}
}
}
arr.splice(0, 2);
return arr.filter((val) => {
return !!val;
}).reduce((sum, val) => {
return sum + val;
}, 0);
}