There several new questions post on Leetcode. I picked 5 of them to practice yesterday. The solutions are pretty straightforward. Therefore, I just post my comments on after the code, instead of posting a long paragraph to explain.
No.1 Happy Number
Write an algorithm to determine if a number is “happy”. A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example: 19 is a happy number
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
12 + 0^2 + 0^2 = 1
My Solution
1 | class Solution { |
No.2 Isomorphic Strings
Given two strings s and t (same length), determine if they are isomorphic. Two strings are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.
For example,
Given “egg”, “add”, return true.
Given “foo”, “bar”, return false.
Given “paper”, “title”, return true.
My Solution
1 | class Solution { |
No.3 Count Prime Numbers
#####Question:
Count the number of prime numbers less than a non-negative number, n.
This solution is based on Sieve of Eratosthenes, which might sound too academic, but actually pretty straightforward.
My Solution [Time: O(n) Space:O(n) ]
1 | class Solution { |