← All problems

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

EasyOpen on LeetCodeProblem statement

Problem Statement

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:

Java

Source file
class Solution {
    public boolean hasSameDigits(String s) {
        StringBuilder sb = new StringBuilder(s);
        int n = sb.length();
        while (n > 2) {
            s = sb.toString();
            sb.setLength(0);
            for (int i = 0; i < n - 1; i++)
                sb.append((s.charAt(i) + s.charAt(i + 1) - 2 * '0') % 10);
            n = sb.length();
            // System.out.println(sb);
        }
        return sb.charAt(0) == sb.charAt(1);
    }
}