알고리즘/해결

LeetCode1295. Find Numbers with Even Number of Digits

언클린 2020. 2. 2. 20:23
728x90

1. 문제(원본)

Given an array nums of integers, return how many of them contain an even number of digits.

 

Example 1:

Input: nums = [12,345,2,6,7896]

Output: 2

Explanation: 12 contains 2 digits (even number of digits).  345 contains 3 digits (odd number of digits).  2 contains 1 digit (odd number of digits).  6 contains 1 digit (odd number of digits).  7896 contains 4 digits (even number of digits).  Therefore only 12 and 7896 contain an even number of digits.

 

Example 2:

Input: nums = [555,901,482,1771]

Output: 1

Explanation: Only 1771 contains an even number of digits.

 

Constraints:

  • 1 <= nums.length <= 500
  • 1 <= nums[i] <= 10^5

2. 문제

Int형 배열을 받아 자릿수가 짝수인 인덱스를 카운트 하여 반환 

 

3. 나의 답

class Solution {

    func findNumbers(_ nums: [Int]) -> Int {

        func countOfDigit(_ number: Int) -> Int {

            var num = number

            var count: Int = 0

            while num > 0 {

                num /= 10

                count += 1

            }

            return count

        }

        

        var count = 0

        for element in nums {

            if countOfDigit(element) % 2 == 0 {

                count += 1

            }

        }

        return count

    }

}

4. 다른 유저의 답

#1

class Solution {

    func findNumbers(_ nums: [Int]) -> Int {

        var evenNumber = 0;

        for num in nums {

            var count = (Array(String(num)).count % 2) == 0 ? 1 : 0;

            evenNumber += count;

        }

        return evenNumber;

    }

}

#2

public func findNumbers(_ nums: [Int]) -> Int {

    var count = 0

    for i in nums {

        count += String(i).count % 2 == 0 ? 1 : 0

    }

    return count

}

5. 마무리

String으로 형변환 해서 할 수 있는 방법을 생각하지 못하고 직접 각 인덱스의 자릿수를 구했다.

Int형과 String형은 자주 같이 생각하는 편이 좋을 것 같다.

728x90