LeetCode Solution, Easy, 1295. Find Numbers with Even Number of Digits

尋找具有偶數位數的數字

1295. Find Numbers with Even Number of Digits

題目敘述

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

Hint 1

How to compute the number of digits of a number ?

Hint 2

Divide the number by 10 again and again to get the number of digits.

題目翻譯

要在一個陣列 nums 中找出總共有幾個數值的位數是偶數的。

解法解析

這邊使用數字轉換字串的方是來解,轉換成字串後就可以用 % 2 來判斷是否為偶數。另外一種方式就是用雙重回圈的方式來 / 10 計算總共有幾個位數。

解法範例

Go

func findNumbers(nums []int) int {
    var count int = 0
    for _, num := range nums {
        if len(strconv.Itoa(num))%2 == 0 {
            count++
        }
    }
    return count
}

JavaScript

/**
 * @param {number[]} nums
 * @return {number}
 */
var findNumbers = function(nums) {
    let count = 0;
    for (const num of nums) {
        count += ~String(num).length & 1
    }
    return count;
};

Kotlin

class Solution {
    fun findNumbers(nums: IntArray): Int {
        var count: Int = 0
        for (num in nums) {
            if (num.toString().length % 2 == 0) {
                count++
            }
        }
        return count
    }
}

PHP

class Solution
{

    /**
     * @param Integer[] $nums
     * @return Integer
     */
    function findNumbers($nums)
    {
        $count = 0;
        foreach ($nums as $num) {
            if (strlen((string)$num) % 2 == 0) {
                $count++;
            }
        }
        return $count;
    }
}

Python

class Solution:
    def findNumbers(self, nums: List[int]) -> int:
        return sum(~len(str(x)) & 1 for x in nums)

Rust

impl Solution {
    pub fn find_numbers(nums: Vec<i32>) -> i32 {
        return nums.iter()
            .filter(|num| num.to_string().len() %2 == 0)
            .count() as i32;
    }
}

Swift

class Solution {
    func findNumbers(_ nums: [Int]) -> Int {
        var count: Int = 0
        for num in nums {
            if String(num).count % 2 == 0 {
                count += 1
            }
        }
        return count
    }
}

Did you find this article valuable?

Support 攻城獅 by becoming a sponsor. Any amount is appreciated!