[코테 풀이] Count Symmetric Integers

시내·2024년 6월 30일

Q_2843) Count Symmetric Integers

출처 : https://leetcode.com/problems/count-symmetric-integers/

You are given two positive integers low and high.

An integer x consisting of 2 * n digits is symmetric if the sum of the first n digits of x is equal to the sum of the last n digits of x. Numbers with an odd number of digits are never symmetric.

Return the number of symmetric integers in the range [low, high].

class Solution {
    public int countSymmetricIntegers(int low, int high) {
        int count = 0;
        for (int i = low; i <= high; i++) {
            String s = Integer.toString(i);
            if (s.length() % 2 == 0) {
                int n = s.length() / 2;
                int first = 0;
                int second = 0;
                for (int a = 0; a < n; a++) {
                    first += s.charAt(a) - '0';
                    second += s.charAt(s.length() - a - 1) - '0';
                }
                if (first == second) count++;
            }
        }
        return count;
    }
}
profile
contact 📨 ksw08215@gmail.com

0개의 댓글