[Επιλύθηκε] Character Multiplier - String Task

  

3
Εκκινητής θέματος

Create a method that takes two strings as arguments and returns the sum of their character codes multiplied (multiply str1[0] with str2[0] and add to the total sum).

Then continue with the next two characters. If one of the strings is longer than the other, add the remaining character codes to the total sum without multiplication.

Παραδείγματα:

character multiplier string task

1 Απάντηση
2

Nice task!

I've used this ASCII table:

ASCII table chars ascii values

and this is my code:

<?php
 
$args = explode(" ", readline());
 
$word1 = $args[0];
$word2 = $args[1];
 
$min = min(strlen($word1), strlen($word2));
 
$sum = 0;
 
for ($i = 0; $i < $min; $i++) {
    $code1 = ord($word1[$i]);//$word1: ASCII codes of the letters
    $code2 = ord($word2[$i]);//$word2: ASCII codes of the letters
    $sum += $code1 * $code2;
}
 
$remaining = '';
 
if (strlen($word2) > strlen($word1)) {
    $remaining = substr($word2, $min);
} else {
    $remaining = substr($word1, $min);
}
 
for ($i = 0; $i < strlen($remaining); $i++) {
    $code3 = ord($remaining[$i]);
    $sum += $code3;
}
 
echo $sum;
Μοιράσου: