JavaScript implementation algorithm

Source: Internet
Author: User
Tags pow

Off Topic

After brushing the Codewars JavaScript topic for a while, it gives me the greatest feeling that will help you to quickly improve the familiarity of the APIs that you want to practise, the native methods of array objects, string objects, constructors, some algorithmic questions, and so On. After each submit, look at your code, and then look at the code that someone else Wrote. Find yourself writing code and implementation ideas are simply Weak. so, every time after submi, will look at the top five answer, understand Daniel's problem solving ideas (in Most cases, the code will use ES6 syntax, very concise), and then train again. In this way, it has been practiced for almost 20 days. This is my achievements in the codewars, 5kyu, brushed 93 questions, Some of the problems are unexpectedly, unlock Solutions. So honor completed kata is not 100%.

Recently began to play leetcode, change a plaform mainly because Leetcode on the topic is mostly the major Internet companies interview topics, and mostly biased algorithm. It happened that I was eager to improve my ability in this area recently. So transferred the plaform, although I somewhat do not shed: "(. But I will continue to play Codewars

1-20 Leetcode personal Problem solving ideas


Implementation Idea: create an empty array and write a two-layer loop. The variable initialization for the Second-tier loop is based on the first loop. Then make a judgment, if nums[i] + nums[j] = = = target, exit the Loop.

var twoSum = function(nums, target) {    index = [];    for (let i = 0; i < nums.length; i++) {        for (let j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] === target) { index.push(i); index.push(j); break; } }} return index;};
ZigZag Conversion (difficulty:easy; Tags:string)


First of all, to complete this topic, we need to understand that. How ZigZag pattern relates to the number of rows Given.

Very simple, with only 2 rows, 3 rows, and 4 rows, The shape of the zigzag is as follows

The main idea of this topic is to understand the relationship between a given number of rows and the position of letters that need to be extracted in each ROW.

    1. Returns the original string directly when there is only one row
    2. When greater than one line, the first and last lines of the same law, that is (assuming that the specified number of rows is n, at this time n>1) each circle (code a value) is every [n-(n-2)] * (n-1) a position appears once
    3. In addition to the first and last lines, the distribution of the median circle is also regular: the last value of the blue arrow is 2 * (n-1) from the previous value, and the two values of the green arrow follow this Pattern. therefore, The implementation code is as follows

var convert =functions, Numrows) {if (numrows = = =1)Return s;Let str =‘‘;Let num = (numrows-(numrows-2)) * (numrows-1);2for (Let i =1; I <= numrows; I++) {for (Let J = i-1; J < s.length; J + = Num) {if (i = = =1 | | i = = Numrows) {str + = S.slice (j, j +1); }else {str + = S.slice (j, j +1); str + = S.slice (j + num-(2 * (i-1)), j + Num-(2 * (i-1)) + 1); }}} return str;}; console.log (convert ( "123456789", 2)); //135792468console.log (convert (  "123456789", 3); //159246837console.log (convert (  "123456789", 4); //172683594console.log (convert (  "1234567891234567891234", 5); //1982817937261463524543           


This topic is very interesting, the topic is very direct, let us put the reference of input Reverse. But there is a requirement, that is, if the value of reverse exceeds 32bit, it will return 0.

The idea is to use JS or arithmetic |, the ascended operator, to convert the value of reverse to 32 bits, and then compare it to the original Value.

Math.pow(2, 32)|0Returns 0 (Math.pow(2, 32) + 1)|0 returns 1. So the logic of solving the problem

var reverse =function (x) {let str1 = x.tostring (). match (/[0-9]/g). reverse (). Join ( let str2 = x.tostring (). match (/[^0-9]/g) = = = null? /[^0-9]/g). Join ( let num1 = number (str2 + str1) | 0; //reverse and transform to 32bit let num2 = number (STR2 + str1); return num1 = = = num2? num2: 0;};     

This topic mainly examines the understanding of the data type Nan and the understanding of the method isNaN (), and examines the difference between the number, parseint, and parsefloat methods. Here's a simple Statement.

NaN

NaN, or Non-numeric (not a number) is a special value that represents an operand that would have returned a numeric value.
No value is returned (this will not throw an error). Any number divided by 0 will return Nan.

Nan is not equal to any value, including the Nan Itself. Soconsole.log(NaN === NaN) // false

isNaN is used to determine if a parameter is "not a value".

parseint

Parseint and parsefloat are used to convert a string to a numeric type, and number is used to convert any data type, here is the main introduction to Parseint.

parseint ignores whitespace in front of the string until a non-whitespace character is found. If the first character is not a numeric character or a minus or a plus sign, parseint returns NAN. That is, converting an empty string with parseint () returns nan (number () to null character returns 0) if the first character is a numeric character, parseint () continues to parse the second character until all subsequent characters have been parsed or a non-numeric character is Encountered. For example, "1234blue" is converted to 1234 because "blue" is completely ignored. similarly, "22.5" is converted to 22 because the decimal point is not a valid numeric character; '-123 ' is converted To-123 because the first character is a minus sign and the subsequent character is a number; '-+123 ' returns nan because the first character Is-and the second character is +, does not conform to the normal numeric pattern.

therefore, the solution to the problem is as Follows:

var myatoi =functionStr) {Let symbol =‘‘; str = str.replace (/^\s+|\s+$/g,‘‘);Remove both ends of the space str =IsNaN (parseint (str))?0: parseint (str); if (str > math.pow (2, + )- 1) { return Math.pow (2, + )- 1;} Else if (str <- Math.pow (2, + )) { return- math.pow (2, 31);} else { return str;}};               

Continuous update ...

Tags: Leetcode

JavaScript implementation algorithm

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.