CodeWars 코딩 문제 2021/01/24 - Upside down numbers

이호현·2021년 1월 24일
0

Algorithm

목록 보기
62/138

[문제]

Consider the numbers 6969 and 9116. When you rotate them 180 degrees (upside down), these numbers remain the same. To clarify, if we write them down on a paper and turn the paper upside down, the numbers will be the same. Try it and see! Some numbers such as 2 or 5 don't yield numbers when rotated.

Given a range, return the count of upside down numbers within that range. For example, solve(0,10) = 3, because there are only 3 upside down numbers >= 0 and < 10. They are 0, 1, 8.

More examples in the test cases.

(요약) 주어진 범위안의 숫자를 시계방향으로 180도 돌렸을 때, 원래 숫자와 같은 숫자 개수를 찾아라.

function solve(x, y) {
  let answer = 0;
  let check = true;
  const updown = {
    '1': '1',
    '6': '9',
    '8': '8',
    '9': '6',
    '0': '0'
  };

  for(let i = x; i < y; i++) {
    const numToStr = `${i}`;
    if(numToStr.includes('2') || numToStr.includes('3') || numToStr.includes('4') || numToStr.includes('5') || numToStr.includes('7')) {
      continue;
    }
    else {
      const changeNum = `${i}`.split('').reverse().join('');
      check = true;

      for(let k in changeNum) {
        if(`${i}`[k] !== updown[changeNum[k]]) {
          check = false;
          break;
        }
      }

      if(check) answer++;
    }
  }

  return answer;
};

우선 반전 되는 숫자들을 객체로 만들고, 주어진 범위안에서 숫자들을 이용하기 위해 반복문을 이용함.
숫자를 뒤집는 효과를 만들기 위해 숫자순서를 뒤집고, 각 숫자를 뒤집었을때 바뀌는 숫자로 변경.
그리고 같은 것만 찾아서 그 개수를 return.

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

0개의 댓글