Exes and Ohs

samuel Jo·2023년 6월 27일
0

codewars

목록 보기
25/46

Check to see if a string has the same amount of 'x's and 'o's. The method must return a boolean and be case insensitive. The string can contain any char.

Examples input/output:
XO("ooxx") => true
XO("xooxx") => false
XO("ooxXm") => true
XO("zpzpzpp") => true // when no 'x' and 'o' is present should return true
XO("zzoo") => false

/**첫번째 방법은 o와 x의 갯수를 세어 그값을 비교하는 방법*/
// function XO(str) {
//     // 대문자로 변환
//     str = str.toUpperCase();
  
//     // 'o'와 'x'의 개수 세기
//     let countO = 0;
//     let countX = 0;
//     for (let i = 0; i < str.length; i++) {
//       if (str[i] === 'O') {
//         countO++;
//       } else if (str[i] === 'X') {
//         countX++;
//       }
//     }
  
//     // 개수 비교
//     return countO === countX;
//   }
  
//   console.log(XO("ooxx")); // true
//   console.log(XO("ozzo")); // false

/** x가 있을때 후위 연산자를 통해 0이 나오면 true를 나오게끔 만듦. */
  function XO(str) {
      let sum = 0;
      for(var i=0; i<str.length; i++){
        //1. x가 있을때 1더하기 
      if(str[i].toLowerCase() === 'x') sum--;
      //2. o가 있을때 -1하기
      // ex) "xo" 0++ --; (0+1-1 = 0)
      if(str[i].toLowerCase() === 'o') sum++;
    }
    return sum == 0;
  }
  console.log(XO("ooxx")); // true
  console.log(XO("zzooxxx")); // false
profile
step by step

0개의 댓글