The Love-Letter Mystery

Sort by

recency

|

980 Discussions

|

  • + 0 comments

    My answer with Typescrippt, simple

    function theLoveLetterMystery(s: string): number {
        let operations = 0
    
        // Calculate the sum of the differences between opposite pairs of characters (number ascii).
        for (let i = 0; i < Math.floor(s.length / 2); i++) {
            let reverse_i = s.length - i - 1
            if (s[i] != s[reverse_i]) {
                operations += Math.abs(s.charCodeAt(i) - s.charCodeAt(reverse_i))
            }
        }
    
        return operations
    }
    
  • + 0 comments

    Java 15

    public static int theLoveLetterMystery(String s) {
        // Write your code here
        int count = 0;
            StringBuilder sb = new StringBuilder(s);
            String str = sb.reverse().toString();
            if (s.contentEquals(str)) {
                return count;
            } else {
                for (int i = 0; i < s.length() / 2; i++) {
                    count += Math.abs(s.charAt(i) - s.charAt(s.length() - 1 - i));
                }
                return count;
            }
        }
    
  • + 0 comments

    C++:

    int theLoveLetterMystery(string s) {
        int cnt = 0;
        int k = 0;
        int left_part = 0;
        int right_part = 0;
        while (k < int(s.size() / 2)) {
            left_part = int(s[k]);
            right_part = int(s[s.size() - k - 1]);
            while (left_part != right_part) {
                if (left_part < right_part) {
                    cnt++;
                    right_part -= 1;
                } else if (left_part > right_part) {
                    cnt++;
                    left_part -= 1;
                }
            }
            k++;
        }
        return cnt;
    }
    
  • + 0 comments

    Perl solution:

    sub theLoveLetterMystery {
        my @s = split("", shift);
        my $cnt = 0;
        my $k = 0;
        my $left_part = 0;
        my $right_part = 0;
        while ($k < int(scalar(@s) / 2)) {
            $left_part = ord($s[$k]);
            $right_part = ord($s[scalar(@s) - $k - 1]);
            while ($left_part != $right_part){
                if ($left_part < $right_part) {
                    $cnt++;
                    $right_part -= 1;
                } elsif ($left_part > $right_part) {
                    $cnt++;
                    $left_part -= 1;
                }
            }
            $k++;
        }
        return $cnt;
    
    }
    
  • + 0 comments

    Java:

    public static int theLoveLetterMystery(String s) {
      int n = s.length();
      int totalOps = 0;
    
      for (int i = 0; i < n / 2; i++) {
        totalOps += Math.abs(s.charAt(i) - s.charAt(n - 1 - i));
      }
    
      return totalOps;
    }