[Code Signal][js] isLucky

8114 ワード

🎆質問する


Ticket numbers usually consist of an even number of digits. A ticket number is considered lucky if the sum of the first half of the digits is equal to the sum of the second half.
Given a ticket number n, determine if it's lucky or not.

Example


For n = 1230 , the output should beisLucky(n) = true ;
For n = 239017 , the output should beisLucky(n) = false .

🎇に答える

function isLucky(n) {
    const strArr = String(n).split('');
    const firstArr = strArr.slice(0,strArr.length/2);
    const secondArr = strArr.slice(strArr.length/2);

    for(i=0; i<firstArr.length; i++) {
        firstArr[i] = Number.parseInt(firstArr[i])
    }
    for(i=0; i<secondArr.length; i++) {
        secondArr[i] = Number.parseInt(secondArr[i])
    }
    const sumFirstArr = firstArr.reduce((sum, curr) => {
        return sum + curr;
    })
    const sumSecondArr = secondArr.reduce((sum, curr) => {
        return sum + curr;
    })

    return sumFirstArr === sumSecondArr;
}

置換

function isLucky(n) {
    var count = 0;
    n = String(n).split('').map(t => {return parseInt(t)});
    n.forEach( (el, i) => { (i < n.length / 2) ? count += el : count -= el });
    return count == 0;
}
私はどうして地図をデジタルにしないのですか?
ちゃんと返事を書かなかったからですか?
書くときも非効率で面倒なコードだと思うので、ぜひ他の解答を参考に勉強してみてください.