Ask Question

Write a function string middle (string str) that returns a string containing the middle character in str if the length of str is odd, or the two middle characters if the length is even. For example, middle ("middle") returns "dd".

+2
Answers (1)
  1. 21 August, 20:13
    0
    function getMiddle (s) {

    return s. length % 2? s. substr (s. length / 2, 1) : s. substr ((s. length / 2) - 1, 2);

    }

    / / I/O stuff

    document. getElementById ("submit"). addEventListener ("click", function () {

    input = document. getElementById ("input"). value;

    document. getElementById ("output"). innerHTML = getMiddle (input);

    });

    Explanation:

    / / >>> is an unsigned right shift bitwise operator. It's equivalent to division by 2, with truncation, as long as the length of the string does not exceed the size of an integer in jа vascript.

    / / About the ~ operator, let's rather start with the expression n & 1. This will tell you whether an integer n is odd (it's similar to a logical and, but comparing all of the bits of two numbers). The expression returns 1 if an integer is odd. It returns 0 if an integer is even.

    / / If n & 1 is even, the expression returns 0.

    / / If n & 1 is odd, the expression returns 1.

    / / ~n & 1 inverts those two results, providing 0 if the length of the string is odd, and 1 if the length of the sting is even. The ~ operator inverts all of the bits in an integer, so 0 would become - 1, 1 would become - 2, and so on (the leading bit is always the sign).

    / / Then you add one, and you get 0+1 (1) characters if the length of the string is odd, or 1+1 (2) characters if the length of the string is even.
Know the Answer?
Not Sure About the Answer?
Find an answer to your question 👍 “Write a function string middle (string str) that returns a string containing the middle character in str if the length of str is odd, or ...” in 📗 Computers & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers