CodeWars 코딩 문제 2021/01/20 - Char Code Calculation

이호현·2021년 1월 20일
0

Algorithm

목록 보기
59/138

[문제]

Given a string, turn each character into its ASCII character code and join them together to create a number - let's call this number total1:

Then replace any incidence of the number 7 with the number 1, and call this number 'total2':

Then return the difference between the sum of the digits in total1 and total2:

(요약) 인자로 받은 문자열 각 요소를 아스키코드로 변환하고, 7을 1로 바꾼 후, 바꾸기 전과 후의 모든 자리수를 더해서 차를 구하라.

[풀이]

function calc(x){
  let charCodeStr = '';
  let sevenCount = 0;

  for(let i = 0; i < x.length; i++) {
    let charCode = x[i].charCodeAt() + '';
    charCodeStr += charCode;

    if(charCode.includes('7')) {
      for(let j = 0; j < charCode.length; j++) {
        charCode[j] === '7' && sevenCount++;
      }
    }
  }

  return sevenCount * 6;
}

charCodeAt()으로 각 문자열의 아스키코드를 구해서 문자열로 만들고, 7이 있으면 그 개수를 sevenCount에 카운트함.
71로 바꾼후 모든 자리 수 더한값의 차니까 7의 개수만큼 6을 곱해주면 됨.

profile
평생 개발자로 살고싶습니다

0개의 댓글