Given an array nums of integers, return how many of them contain an even number of digits.
정수로 이루어진 배열이 주어질때, 짝수 자릿수를 가진 요소의 수를 반환하라.
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.
Input: nums = [555,901,482,1771]
Output: 1
Explanation:
Only 1771 contains an even number of digits.
맨 처음 푼 방식은 힌트를 보고 바로 생각나는 대로 풀어보았다.
nums를 하나씩 돌면서 10으로 나눠서 몫이 0이면 자릿수=1이므로 다음 요소를 가져오고 0이 아니면 10의자리 수이므로 자릿수+=1을 해준다. 몫이 10 이상이면 자릿수+=1 를 반복하고 마지막에 자릿수 % 2 == 0, 즉 자릿수가 짝수일 경우에 count++를 해주었다.
class Solution {
public int findNumbers(int[] nums) {
int count = 0;
for (int i = 0; i < nums.length; i++){
int digit = 1;
int condition = nums[i] / 10;
if(condition <= 0){
continue;
}else{
digit++;
}
while(condition >= 10){
condition = condition / 10;
digit++;
}
if (digit % 2 == 0) count++;
}
return count;
}
}
근데 이렇게 하면 반복문 안에 또 반복문이 돌아가기도 하고 코드가 너무 길어지는것 같아서 다른 방법들을 찾아보았다.
그 중 하나가 제약조건을 사용해서 푸는 방법인데 배열의 요소로 오는 정수의 범위가 1~10^5이기 때문에 짝수 자릿수가 될 수 있는 수는 10~99, 1000~9999, 100000 밖에 없다. 그래서 배열을 돌면서 이 수들인 경우에만 count++ 해주면 아주 쉽게 답을 구할 수 있다.
//제약 조건을 사용한 풀이
class Solution {
public int findNumbers(int[] nums) {
int count = 0;
for (int n : nums)
if(n>9 && n<100 || n>999 && n<10000 || n==100000) count++;
return count;
}
}
다른 방법은 그냥 손으로 풀었으면 당연하게 사용했을 방법이다.
먼저 배열을 문자열로 바꾸고 문자열의 길이를 구한다. 길이가 홀수면 당연히 홀수 자릿수, 짝수면 짝수 자릿수 숫자이다.
홀수 자릿수는 길이 % 2 = 1
이니까 1-1=0을, 짝수 자릿수는 길이 % 2 = 0
이니까 1-0=1을 count에 더해주면 된다.
//숫자의 길이가 짝수면 더해주는 방식
class Solution {
public int findNumbers(int[] nums) {
int count = 0;
for (int n : nums)
count += 1 - Integer.toString(n).length() % 2;
return count;
}
}