Don't LeetCode Yet - 1&2 - Think First
Think Before You Code
Think about the processes thoroughly, organize and write down Flowchart (execution steps) and/or Pseudocode before actually coding.
One process each line. Expression, Condition, Repetition.
Some Examples
Print out even integers from 1 to 100
Let theNumber equals to 1 |
pseudocode:
1 let theNumber = 1 |
also:
for theNumber from 1 to 100 |
Indent each section in the code makes the code more readable. Like the for, if and print section above.
Fizz Buzz
Print fizz
if the number is multiple of 3, print buzz
if the number is multiple of 5, and print fizzbuzz
if the number is multiple of 3 and 5.
Some brute force solutions and some BETTER solutions (String Concatenation, Hash).
Find the smallest card
let smallCard = firstCard |
Project 1
Reverse String
let outputStr = ""
for i from stringLength to 0
outputStr += originalStr[i]
print outputStrArray sum
let result = 0
for i from 1 to array length
result += array[i]
print the resultFind the biggest
let the bigCard = the firstCard
for i from 1 to total cards number
if card i > bigCard
bigCard = card i
Computational Thinking
Think one step at a time. Read a piece of code and try to execute the code line by line in your head.
Useful tips for reading the code
Use Chrome Devtool Debugger
Just add the word debugger
in the beginning of the JavaScript code.
For Firefox Devtool. Need to set a break point by clicking on the line number at the left of the code.
These Devtools can run the code step by step
Console.log
everything
When console.log out an array, we can STRINGIFY (JSON.stringify()
) it to show the actual content at that moment (but not the one that has been modified latter).
Examples
Find second large
let max = -Infinity
//but not array[0].
// Or else there will be some problem finding solution.
let max2 = -InfinityLower case string to Upper case
Some knowledge about ASCII code
ASCII code:
a: 97 z:122 A:65 Z:90 (add 32 to exchange Upper case to lower case.)
Function in JavaScript
"a".charCodeAt(0)
will give the ASCII code for “a”
String.fromCharCode("a".charCodeAt(0) - 32)
this will get the character “A”
s.toUpperCase()
shortcut!Delete a certain character
Project 2
Observe the structure of the code.
Write down the execution step by step by reading the code.
- Find Second max
- Lower Upper case exchange
- Find the divisor of a number
Em…here are the solutions:ALG101-too-weak-to-leetcode/unit2