알고리즘

[Leetcode] Find Numbers with Even Number of Digits

JUNGKEUNG 2021. 9. 12. 13:22

https://leetcode.com/explore/learn/card/fun-with-arrays/521/introduction/3237/

 

Explore - LeetCode

LeetCode Explore is the best place for everyone to start practicing and learning on LeetCode. No matter if you are a beginner or a master, there are always new topics waiting for you to explore.

leetcode.com

문제 

정수로 되어있는 배열이 주어진다. 배열 길이에 짝수가 몇개인지 알아보는 문제이다

 

풀이

class Solution {
    public int findNumbers(int[] nums) {
        int answer = 0;
        
        for (int item : nums){
            if(Integer.toString(item).length() % 2 == 0){
                answer ++;
            }
        }
        return answer;
    }
}

문제에는 nums = [12,345,2,6,7896] 이 주어진다.  처음에는 배열 안에 있는 숫자을 2로 나눠서 짝수로 나오는게 몇개인지 알아보는 문제인줄 알았다. 그게 아니라 12 는 길이가 2 이므로 짝수 345 는 3, 2는 1, 6 도 1, 7896 은 4개이다. 그럼

짝수는 12와 마지막 7896 두개이므로 짝수의 갯수는 2개이다.

 

다른풀이

class Solution {
  public int findNumbers(int[] nums) {
    int count = 0;
    for (int num : nums) {
      count += String.valueOf(num).length() % 2 == 0 ? 1 : 0;
    }
    return count;
  }
}

valueOf() 메서드와 람다식을 이용하여 문제를 풀었다 2로 나누었을때 0이 나오면 1 아니면 0이 나오는 풀이이다

 

valueOf() : 입력받은 인자 값을 지정된 Number 객체형으로 반환한다