코딩테스트 공부
[LeetCode] 2180. Count Integers With Even Digit Sum - 자바스크립트 0628
codevil
2022. 6. 28. 12:33
https://leetcode.com/problems/count-integers-with-even-digit-sum/
Count Integers With Even Digit Sum - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
1부터 주어진 숫자까지의 숫자 중에서 (예시 주어진숫자가 5라면 1,2,3,4,5) 각 자리 숫자의 합이 짝수의 합 (예시, 11=>1+1은 짝수다).
1. answer은 0으로 설정한다
let answer =0
2. 1부너 n까지의 for문을 만든다
for(let i=0; i<n+1;i++){
}
3. 위에서 말한 절차를 실행한다
3-1 숫자를 string으로 만든다
3-2 string을 array로 바꾼다
3-3 array의 각 자리 숫자를 더하고 2로 나누어 0이 되는 경우
3-4 answer를 더한다
if (i.toString().split("").reduce((a, b) => Number(a) + Number(b), 0) % 2 === 0) {
answer++
}
4 answer를 return 한다
전체 풀이
var countEven = function (num) {
let answer = 0
for (let i = 1; i < num + 1; i++) {
if (i.toString()..split("").reduce((a, b) => Number(a) + Number(b), 0) % 2 === 0) {
answer++
}
}
return answer
};
문제를 풀다보니
106ms 26% 밖에 안되었기 때문에 다른사람의 풀이를 보며 풀이를 개선했다.
바로 string화를 시키면서, 0들을 제외했다
var countEven = function (num) {
let answer = 0
const regex = /[0]/g
for (let i = 1; i < num + 1; i++) {
if (i.toString().replace(regex, "").split("").reduce((a, b) => Number(a) + Number(b), 0) % 2 === 0) {
answer++
}
}
return answer
};
85ms 58%만큼 좋아졌다. 0같은 경우 굳이 연산을 더안해도 되기때문에 제외하면 효율이 올라가지만, 만일 02468과 같이 모든 숫자로 한다면, 빼는 과정에서 똑같은 시간이 들기 때문에 좋지 않다.