LeetCode-in-Java

3461. Check If Digits Are Equal in String After Operations I

Easy

You are given a string s consisting of digits. Perform the following operation repeatedly until the string has exactly two digits:

Return true if the final two digits in s are the same; otherwise, return false.

Example 1:

Input: s = “3902”

Output: true

Explanation:

Example 2:

Input: s = “34789”

Output: false

Explanation:

Constraints:

Solution

public class Solution {
    public boolean hasSameDigits(String s) {
        char[] ch = s.toCharArray();
        int k = ch.length - 1;
        while (k != 1) {
            for (int i = 0; i < k; i++) {
                int a = ch[i] - 48;
                int b = ch[i + 1] - 48;
                int d = (a + b) % 10;
                char c = (char) (d + '0');
                ch[i] = c;
            }
            k--;
        }
        return ch[0] == ch[1];
    }
}