快轉到主要內容
  1. LeetCode/

LeetCode 2843: Count Symmetric Integers

·1 分鐘· ·
LeetCode Blog Daily Easy
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試: 2025-04-11

  • 總花費時間:5:00.00

解題思路
#

我原本有考慮使用 Digit DP 來解這題,但注意到題目限制中,最大數字只有到 10^5。

因此,我們其實可以直接用暴力法(brute-force)從 startend 逐一遍歷所有數字。
對每個數字來說,如果是奇數就跳過;如果是偶數,則找出中間的索引,接著比較從開頭到中間與從中間到結尾這兩段數位的總和是否相等。

這種解法的時間複雜度是 O(n),空間複雜度是 O(1)

解法
#

class Solution:
    def countSymmetricIntegers(self, low: int, high: int) -> int:
        
        res = 0
        for num in range(low, high+1):
            str_num = str(num)

            if len(str_num)%2:
                continue
            
            half_index = len(str_num)//2
            if sum(map(int, list(str_num[:half_index]))) == sum(map(int, list(str_num[half_index:]))):
                res+=1

        return res

學習
#

N/A

遇到的問題
#

N/A

相關文章

LeetCode 617: Merge Two Binary Trees
·1 分鐘
LeetCode Blog Daily Easy
LeetCode 解題紀錄
LeetCode 2999: Count the Number of Powerful Integers
·1 分鐘
LeetCode Blog Daily Hard
LeetCode 解題紀錄
LeetCode 3375: Minimum Operations to Make Array Values Equal to K
·1 分鐘
LeetCode Blog Daily
LeetCode 解題紀錄
2022Q4 New Grad Data缺求職紀錄
·3 分鐘
Interview Blog
2024下半年面試經驗整理
Digit Dynamic Programming
·2 分鐘
Algorithm
Digit Dynamic Programming 介紹
LeetCode
LeetCode相關文章