2843. Count Symmetric Integers - Easy

前往題目

想法

  • 訪問所有數字,拆開判斷

思路

  1. 直觀的暴力解

Code

class Solution {
    public int countSymmetricIntegers(int low, int high) {
        int res = 0;

        for (int i = low; i <= high; ++i) {
            String s = String.valueOf(i);
            int len = s.length();

            // Skip odd number of digits
            if (len % 2 != 0) continue;

            // Check if symmetric
            int half = len / 2;
            int left = 0, right = 0;
            // Cal. left and right
            for (int j = 0; j < half; ++j) {
                left += s.charAt(j) - '0';
                right += s.charAt(j + half) - '0';
            }
            
            if (left == right) ++res;
        }

        return res;
    }
}

2843. Count Symmetric Integers - Easy
https://f88083.github.io/2025/04/11/2843-Count-Symmetric-Integers-Easy/
作者
Simon Lai
發布於
2025年4月11日
許可協議