zigzagConversion.js

    0

    0

    This code converts a string to a number. First, it checks if the string is null or if the number of rows is less than 1. If either of these conditions is true, the code returns an empty string. If the number of rows is not 1, the code loops through the string and converts each character to a number. The step value is 2 multiplied by the number of rows - 2, so the code loops through the string twice. The first time, it loops through the string from the beginning to the first character that is greater than or equal to the number 2. The second time, it loops through the string from the second character after the first character that is greater than or equal to the number 2 to the end of the string. The code stores the numbers that are greater than or equal to 2 in a new variable called result. The code then returns the result variable.

    var convert = function(s, numRows) {
          if (s === null || numRows <= 0) {
        return "";
      }
      if (numRows === 1) {
        return s;
      }
    
      let result = "";
    
      const step = 2 * numRows - 2;
    
      for (let i = 0; i < numRows; i++) {
        for (let j = i; j < s.length; j += step) {
          result += s[j];
          if (i != 0 && i != numRows - 1 && j + step - 2 * i < s.length) {
            result += s[j + step - 2 * i];
          }
        }
      }
      return result;
    };
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.