3461. Check If Digits Are Equal in String After Operations I #2330
-
|
Topics: You are given a string
Return Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We need to repeatedly perform operations on a string of digits until only two digits remain. Each operation involves calculating a new digit from each pair of consecutive digits by taking their sum modulo 10, and then replacing the string with these new digits in order. The goal is to determine if the final two digits are the same. Approach
Let's implement this solution in PHP: 3461. Check If Digits Are Equal in String After Operations I <?php
/**
* @param String $s
* @return Boolean
*/
function hasSameDigits($s) {
while (strlen($s) > 2) {
$new_s = '';
for ($i = 0; $i < strlen($s) - 1; $i++) {
$sum = (intval($s[$i]) + intval($s[$i + 1])) % 10;
$new_s .= strval($sum);
}
$s = $new_s;
}
return $s[0] == $s[1];
}
// Test cases
// Example 1
$s1 = "3902";
echo hasSameDigits($s1) ? "true\n" : "false\n"; // Output: true
// Example 2
$s2 = "34789";
echo hasSameDigits($s2) ? "true\n" : "false\n"; // Output: false
?>Explanation:
|
Beta Was this translation helpful? Give feedback.
We need to repeatedly perform operations on a string of digits until only two digits remain. Each operation involves calculating a new digit from each pair of consecutive digits by taking their sum modulo 10, and then replacing the string with these new digits in order. The goal is to determine if the final two digits are the same.
Approach