1.判断NarcissisticNumber,Math.pow 用于计算一个数的指定幂次方
function narcissistic(value) {
// Code me to return true or false
var numstr = value.toString();
var sum = 0
for(var i=0;i<numstr.length;i++){
sum += Math.pow(numstr[i],numstr.length)
}
return sum ==value
}
2. Build a function that returns an array of integers from n to 1 where n>0
.
Example : n=5
--> [5,4,3,2,1]
const reverseSeq = n => {
var list1 = []
for(var i=n; i>=1;i--){
list1.push(i)
}
return list1;
};
3.去掉元音字母
function disemvowel(str) {
var vowels = /[aoeiu]/gi
return str.replace(vowels,"");
}
4.Unique In Order
var uniqueInOrder=function(iterable){
//your code here - remember iterable can be a string or an array
var neworder = []
for(var i=0;i<iterable.length;i++){
if(iterable[i] != iterable[i+1]){
neworder.push(iterable[i])
}
}
return neworder;
}
5.Find the next perfect square!
function findNextSquare(sq) {
// Return the next square if sq is a perfect square, -1 otherwise
var data = Math.pow(sq,0.5)
if(data%1===0){
return (data+1)**2
}
return -1;
}
6.Valid Braces
function validBraces(braces){
//TODO
const stack = []
for(let i=0;i<braces.length;i++){
const brace = braces[i];
if(brace==="(" ||brace==="[" || brace==="{" ){
stack.push(brace)
}else{
if(stack.length===0){
return false
}
const openingBrace = stack.pop();
console.log(stack)
if(
(brace===")" && openingBrace!=="(" )||
(brace==="]" && openingBrace!=="[" )||
(brace==="}" && openingBrace!=="{" )
){
return false;
}
}
}
return stack.length===0;
}
7.Array.diff
function arrayDiff(a, b) {
const c = []
for(let i=0;i<a.length;i++){
let isInB =false
for(let j=0;j<b.length;j++){
if(a[i]===b[j]){
isInB = true
break
}
}
if(!isInB){
c.push(a[i])
}
}
return c
}
8.Playing with digits
function digPow(n, p){
// ...
let f = n.toString()
let testsum = 0
if(n<0 || p<0){
return false
}else{
for (let i=0;i<f.length;i++){
testsum += f[i]**(p+i)
}
if(testsum % n == 0){
let result = testsum/n
console.log(testsum/n)
return result
}else{
return -1
}
}
}
9.The Supermarket Queue
function queueTime(customers, n) {
//TODO
const machinelist = Array(n).fill(0)
for(let i=0; i<customers.length; i++){
const minTimeMachineIndex = machinelist.indexOf(Math.min(...machinelist))
machinelist[minTimeMachineIndex] += customers[i]
}
return Math.max(...machinelist)
}
10.Split Strings
function solution(str){
const substrs = []
if(str.length % 2 ==0){
for(let i=0;i<str.length;i+=2){
const substr = str.substring(i,i+2)
substrs.push(substr)
}
}else{
str = str+"_"
for(let i=0;i<str.length;i+=2){
const substr = str.substring(i,i+2)
substrs.push(substr)
}
}
return substrs
}