[LeetCode-Eazy] Find Numbers with Even Number of Digits

Recording Me Solve This Problem By Golang.

這題主要是累計陣列中數字為偶數的次數,可以透過除以 10 的次數來計算位數是否為偶數。

builtin package - builtin - Go Packages
  • Array: the number of elements in v.
  • Pointer to array: the number of elements in *v (even if v is nil).
  • Slice, or map: the number of elements in v; if v is nil, len(v) is zero.
  • String: the number of bytes in v.
  • Channel: the number of elements queued (unread) in the channel buffer;
    if v is nil, len(v) is zero.

Golang 中只有以上五種東西可以用 len() 算出長度

Golang

func iterativeDigitsCount(number int) int {
	count := 0
	for number != 0 {
		number /= 10
		count += 1
	}
	return count
}
func findNumbers(nums []int) int {
	r := 0
	for i := 0; i < len(nums); i++ {
		n := iterativeDigitsCount(nums[i])
		n %= 2
		if (n) == 0 {
			r++
		}
	}
	return r
}

Python

Convert to string

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

Calculate the number of times divided by 10

class Solution:
    def findNumbers(self, nums: List[int]) -> int:
        def isEven(n):
            count = 0
            while n > 0:
                n //= 10
                count += 1
            return count % 2 == 0
        res = 0
        for n in nums:
            if isEven(n):
                res += 1
        return res