[LeetCode] Check If Digits Are Equal in String After Operations I

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

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

  • For each pair of consecutive digits in s, starting from the first digit, calculate a new digit as the sum of the two digits modulo 10.
  • Replace s with the sequence of newly calculated digits, maintaining the order in which they are computed.

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
bool hasSameDigits(string s) {
while(s.length() > 2) {
string ss = "";
for(int i = 0; i < s.length() - 1; i++) {
int digit = (s[i] - '0' + s[i+1] - '0') % 10;
ss.push_back(digit + '0');
}
swap(s,ss);
}
return s[0] == s[1];
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/02/23/PS/LeetCode/check-if-digits-are-equal-in-string-after-operations-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.