[Leetcode] 1295. Find Numbers with Even Number of Digits

whitehousechef·2025년 4월 30일

https://leetcode.com/problems/find-numbers-with-even-number-of-digits/description/?envType=daily-question&envId=2025-04-30

initial

an extremely easy q

class Solution:
    def findNumbers(self, nums: List[int]) -> int:
        ans = 0
        for num in nums:
            if len(str(num))%2==0:
                ans+=1
        return ans

sol

actually there is a better logic
we know from 0~9 it is odd
10~99 is even
100~999 is odd
and so on and we can set the constraints like this

class Solution {
    public int findNumbers(int[] nums) {
        
        int count=0;
        
        for(int i =0 ; i< nums.length; i++){
            
            if((nums[i]>9 && nums[i]<100) || (nums[i]>999 && nums[i]<10000) || nums[i]==100000){
                count++;
            }
        }
        
        return count;
        
    }
}

complexity

n time
1 space

0개의 댓글