diff --git a/counting-bits/Leo.py b/counting-bits/Leo.py new file mode 100644 index 000000000..ec1142d5d --- /dev/null +++ b/counting-bits/Leo.py @@ -0,0 +1,11 @@ +class Solution: + def countBits(self, n: int) -> List[int]: + counter = [0] + + for i in range(1, n + 1): + counter.append(counter[i >> 1] + i % 2) + + return counter + + ## TC: O(n), SC: O(n) + ## this question should be under math section tbh diff --git a/counting-bits/WhiteHyun.swift b/counting-bits/WhiteHyun.swift new file mode 100644 index 000000000..2eca4a743 --- /dev/null +++ b/counting-bits/WhiteHyun.swift @@ -0,0 +1,27 @@ +// +// 338. Counting Bits +// https://leetcode.com/problems/counting-bits/description/ +// Dale-Study +// +// Created by WhiteHyun on 2024/05/19. +// + +final class Solution { + + // MARK: - Time Complexity: O(n), Space Complexity: O(n) + + func countBits(_ n: Int) -> [Int] { + var array: [Int] = .init(repeating: 0, count: n + 1) + for i in stride(from: 1, through: n, by: 1) { + array[i] = array[i >> 1] + (i & 1) + } + return array + } + + // MARK: - nonzeroBitCount + + func countBits2(_ n: Int) -> [Int] { + return (0...n).map(\.nonzeroBitCount) + } + +} diff --git a/counting-bits/bhyun-kim.py b/counting-bits/bhyun-kim.py new file mode 100644 index 000000000..0e5332e7b --- /dev/null +++ b/counting-bits/bhyun-kim.py @@ -0,0 +1,65 @@ +""" +338. Counting Bits +https://leetcode.com/problems/counting-bits/description/ + +Solution 1: + - Convert the number to binary string + - Sum the number of 1s in the binary string + - Append the sum to the output list + - Return the output list + +Time complexity: O(nlogn) + - The for loop runs n times + - The sum function runs O(logn) times + +Space complexity: O(n) + - The output list has n elements + +class Solution: + def countBits(self, n: int) -> List[int]: + output = [] + for i in range(n + 1): + _str = str(bin(i))[2:] + _sum = sum(map(int, _str.strip())) + output.append(_sum) + + return output +""" + +""" +Solution 2 + We can solve this problem with dynamic programming. + 1. Initialize output with n elements + 2. The first element is 0 because iteration starts from zero. + 3. Iterate from 1 to n+1 + 4. The last digit of each number is 0 for even number 1 for odd number + So add (i & 1) to the output + 5. The digits except the last one can be found when the number is divided by two. + Instead for division by two, we can use one step of bit shift to the right. + + 0 = 00000 + 1 = 00001 + 2 = 00010 + 3 = 00011 + 4 = 00100 + 5 = 00101 + 6 = 00110 + 7 = 00111 + +Time complexity: O(n) + - The for loop runs n times + +Space complexity: O(n) + - The output list has n elements +""" + +from typing import List + +class Solution: + def countBits(self, n: int) -> List[int]: + output = [0] * (n+1) + + for i in range(1, n+1): + output[i] = output[i >> 1] + (i & 1) + + return output diff --git a/counting-bits/invidam.go.md b/counting-bits/invidam.go.md new file mode 100644 index 000000000..e51fb67b3 --- /dev/null +++ b/counting-bits/invidam.go.md @@ -0,0 +1,45 @@ +# Intuition + +이전 값들을 재활용한다. +# Approach + +1. 엣지 케이스는 0을 반환한다. +2. 0, 1을 미리 계산한다. +3. `>>`을 수행한 결과 + 짝/홀 여부로 인한 1을 더해서 해결해준다. +- 이진수 `1001`의 경우 `100` 계산한 결괏값에서 `1`을 더해주면 된다. +- 이진수 `1010`의 경우 `101` 계산한 결괏값에서 `0`을 더해주면 된다. + +- 솔루션 참고: `i & (i-1)` 연산을 통해 계산한다. + - 2의 제곱수인 경우 `0`이 나와 1을 더하면 된다. + - 아닌 경우는 아직은 잘 모르겠다. +# Complexity +- Time complexity: $$O(n)$$ + +:`n`크기의 배열을 모두를 순회한다. +- Space complexity: $$O(n)$$ + +:크기 `n`의 배열을 선언한다. +# Code +```go +func countBits(n int) []int { + if n == 0 { + return []int{0} + } + ans := make([]int, n+1, n+1) + + ans[0], ans[1] = 0, 1 + + for i := 2; i <= n; i++ { + ans[i] = ans[i>>1] + i&1 + } + return ans +} + +func countBitsSolution(n int) []int { + res := make([]int, n+1) + for i := 1; i <= n; i++ { + res[i] = res[i&(i-1)] + 1 + } + return res +} +``` \ No newline at end of file diff --git a/counting-bits/nhistory.js b/counting-bits/nhistory.js new file mode 100644 index 000000000..83e70952e --- /dev/null +++ b/counting-bits/nhistory.js @@ -0,0 +1,26 @@ +var countBits = function (n) { + // Create array which has 0 element length of n + const dp = new Array(n + 1).fill(0); + let offset = 1; + + for (let i = 1; i <= n; i++) { + if (offset * 2 === i) offset = i; + dp[i] = 1 + dp[i - offset]; + } + return dp; +}; + +/** + 0 -> 0000 -> dp[0] = 0 + 1 -> 0001 -> dp[1] = 1 + dp[1-1] = 1 + 2 -> 0010 -> dp[2] = 1 + dp[2-2] = 1 + 3 -> 0011 -> dp[3] = 1 + dp[3-2] = 2 + 4 -> 0100 -> dp[4] = 1 + dp[4-4] = 1 + 5 -> 0101 -> dp[5] = 1 + dp[5-4] = 2 + 6 -> 0110 -> dp[6] = 1 + dp[6-4] = 2 + 7 -> 0111 -> dp[7] = 1 + dp[7-4] = 3 + 8 -> 1000 -> dp[8] = 1 + dp[8-8] = 1 + */ + +// TC: O(n) +// SC: O(1) diff --git a/counting-bits/yolophg.js b/counting-bits/yolophg.js new file mode 100644 index 000000000..093f2edec --- /dev/null +++ b/counting-bits/yolophg.js @@ -0,0 +1,13 @@ +// Time Complexity: O(n) +// Space Complexity: O(n) + +var countBits = function(n) { + // initialize an array to hold the result. + let ans = new Array(n + 1).fill(0); + + // iterate through all numbers from 1 to n. + for (let i = 1; i <= n; i++) { + ans[i] = ans[i >> 1] + (i & 1); + } + return ans; +}; diff --git a/group-anagrams/Leo.py b/group-anagrams/Leo.py new file mode 100644 index 000000000..3aa4f9822 --- /dev/null +++ b/group-anagrams/Leo.py @@ -0,0 +1,22 @@ +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + ans = collections.defaultdict(list) + + for s in strs: + ans[str(sorted(s))].append(s) + + return list(ans.values()) + + ## TC: O(n * klogk), SC: O(n * k), where n is len(strs) and k is len(longest_s) + + # ans = {} + + # for s in strs: + # sorted_s = ''.join(sorted(s)) + + # if sorted_s not in ans: + # ans[sorted_s] = [] + + # ans[sorted_s].append(s) + + # return list(ans.values()) diff --git a/group-anagrams/WhiteHyun.swift b/group-anagrams/WhiteHyun.swift new file mode 100644 index 000000000..18c0ef782 --- /dev/null +++ b/group-anagrams/WhiteHyun.swift @@ -0,0 +1,18 @@ +// +// 49. Group Anagrams +// https://leetcode.com/problems/group-anagrams/description/ +// Dale-Study +// +// Created by WhiteHyun on 2024/05/19. +// + +final class Solution { + func groupAnagrams(_ strs: [String]) -> [[String]] { + var dictionary: [String: [String]] = [:] + for str in strs { + dictionary[String(str.sorted()), default: []].append(str) + } + + return Array(dictionary.values) + } +} diff --git a/group-anagrams/bhyun-kim.py b/group-anagrams/bhyun-kim.py new file mode 100644 index 000000000..7c4970d17 --- /dev/null +++ b/group-anagrams/bhyun-kim.py @@ -0,0 +1,46 @@ +""" +49. Group Anagrams +https://leetcode.com/problems/group-anagrams/description/ + +Solution: + - Create a hash table and a list of counters + - For each string in the input list: + - Sort the string + - If the sorted string is in the hash table: + - Append the string to the corresponding counter list + - Else: + - Add the sorted string to the hash table + - Create a new counter list and append the string + - Return the list of counters + +Time complexity: O(nmlogm) + - The for loop runs n times + - The sorted function runs O(mlogm) times + - m is the length of the longest string in the input list + +Space complexity: O(n) + - The output list has n elements + - The hash table has n elements + - The list of counters has n elements +""" + +from typing import List + + +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + + hash_table = dict() + output = [] + + for s in strs: + count_s = ''.join(sorted(s)) + if count_s in hash_table: + idx = hash_table[count_s] + output[idx].append(s) + else: + hash_table[count_s] = len(output) + output.append([s]) + + return output + diff --git a/group-anagrams/invidam.go.md b/group-anagrams/invidam.go.md new file mode 100644 index 000000000..0505ee2bc --- /dev/null +++ b/group-anagrams/invidam.go.md @@ -0,0 +1,87 @@ +# Intuition +정렬된 문자열을 통해 그룹 여부를 쉽게 확인한다. +# Approach +1. `{정렬된 문자열, 그 문자열의 인덱스}`를 유지하는 배열을 선언한다. +2. 원본 배열을 순회하며 정렬한 결과, 인덱스를 struct로 하여 배열에 삽입한다. + - 인덱스를 유지하는 이유는 원본 배열의 문자열 값을 확인하기 위함이다. (정렬을 했기에 이렇지 않으면 확인이 어렵다.) +3. 모든 struct가 삽입된 배열을 문자열을 기준으로 정렬한다. +4. 반복문을 순회하며 `이전 문자열과 같은지` 여부를 그룹을 판단하여 인덱스들을 그루핑해 모아놓는다. +5. 그루핑한 인덱스들을 문자열(원본 문자열을 참조해서)로 치환하여 최종적으로 반환한다. +# Complexity +- Time complexity: $$O(nklog(n))$$ + +: 배열의 길이 `n`, 문자열의 길이 `k`. 문자열을 기준으로 정렬할 때 발생하는 비용이다. +- Space complexity: $$O(nk)$$ + +: 주어진 배열의 길이 `n`, 배열이 가지는 문자열의 길이 `k`, (코드로 생성하는 배열의 길이, 문자열의 크기 모두 `n`, `k`이다.) + + +# Code +```go +type StrAndIdx struct { + Str string + Idx int +} + +func sortSring(s string) string { + runes := []rune(s) + + sort.Slice(runes, func(i, j int) bool { + return runes[i] < runes[j] + }) + + return string(runes) +} + +func groupAnagrams(strs []string) [][]string { + + strAndIdxs := make([]StrAndIdx, 0, len(strs)+5) + + for i, s := range strs { + strAndIdxs = append(strAndIdxs, StrAndIdx{sortSring(s), i}) + } + + sort.Slice(strAndIdxs, func(i, j int) bool { + return strAndIdxs[i].Str < strAndIdxs[j].Str + }) + + groupedIdxs := make([][]int, 0, len(strAndIdxs)/4) + + group := make([]int, 0) + defaultString := "NOT_EXIST_STRING" + prev := defaultString + for _, sAI := range strAndIdxs { + curr := sAI.Str + idx := sAI.Idx + if prev == curr { + group = append(group, idx) + } else { + if prev != defaultString { + groupedIdxs = append(groupedIdxs, group) + } + group = []int{idx} + } + prev = curr + } + + if len(group) != 0 { + groupedIdxs = append(groupedIdxs, group) + } + + groupedStrs := make([][]string, 0, len(groupedIdxs)) + for _, idxs := range groupedIdxs { + + groupStr := make([]string, 0, len(idxs)) + for _, idx := range idxs { + groupStr = append(groupStr, strs[idx]) + } + groupedStrs = append(groupedStrs, groupStr) + } + + return groupedStrs +} +``` + +# **To** Learn +- GoLang에서 문자열을 어떻게 비교하는지. +- 해당 문제 해결에 있어서 삽질한 것은 무엇이었는지. 앞으로 어떻게 해야 안할 수 있는지. \ No newline at end of file diff --git a/group-anagrams/nhistory.js b/group-anagrams/nhistory.js new file mode 100644 index 000000000..b72bcff0d --- /dev/null +++ b/group-anagrams/nhistory.js @@ -0,0 +1,23 @@ +var groupAnagrams = function (strs) { + // Declare hash map to store sorted strs + let map = new Map(); + + for (let str of strs) { + // Sorted each str + const sortedStr = str.split("").sort().join(""); + + // If there is alread sortedStr on the map, pushed str + if (map.has(sortedStr)) { + map.get(sortedStr).push(str); + } else { + // If there is no sortedStr on the map, insert [str] + map.set(sortedStr, [str]); + } + } + return Array.from(map.values()); +}; + +// TC: O(n*klogk) +// SC: O(n*k) +// n -> length of strs array +// k -> amount of character for each element diff --git a/group-anagrams/yolophg.js b/group-anagrams/yolophg.js new file mode 100644 index 000000000..88e094ad7 --- /dev/null +++ b/group-anagrams/yolophg.js @@ -0,0 +1,25 @@ +// Time Complexity: O(n * k) +// Space Complexity: O(n * k) + +var groupAnagrams = function(strs) { + const map = new Map(); + for (const str of strs) { + // initialize an array to count the frequency of characters. + const count = new Array(26).fill(0); + // increment the count for each character. + for (const char of str) { + count[char.charCodeAt(0) - 'a'.charCodeAt(0)]++; + } + // generate a unique key based on character frequencies. + const key = count.join('#'); + // if the key exists, push the original string to its group. + if (map.has(key)) { + map.get(key).push(str); + } else { // else, create a new group with the key. + map.set(key, [str]); + } + } + + // return the groups of the map as an array. + return Array.from(map.values()); +}; diff --git a/missing-number/Leo.py b/missing-number/Leo.py new file mode 100644 index 000000000..1e6d30127 --- /dev/null +++ b/missing-number/Leo.py @@ -0,0 +1,8 @@ +class Solution: + def missingNumber(self, nums: List[int]) -> int: + n = len(nums) + + return int(n * (n + 1) / 2 - sum(nums)) + + # TC: O(n), SC: O(1) + # this only works for "only missing number", if there are multiple missing numbers, this won't work diff --git a/missing-number/WhiteHyun.swift b/missing-number/WhiteHyun.swift new file mode 100644 index 000000000..0c9f7120e --- /dev/null +++ b/missing-number/WhiteHyun.swift @@ -0,0 +1,30 @@ +// +// 268. Missing Number +// https://leetcode.com/problems/missing-number/description/ +// Dale-Study +// +// Created by WhiteHyun on 2024/05/19. +// + +final class Solution { + func missingNumber(_ nums: [Int]) -> Int { + (0 ... nums.count).reduce(0, +) - nums.reduce(0, +) + } + + func missingNumber2(_ nums: [Int]) -> Int { + nums.count * (nums.count + 1) / 2 - nums.reduce(0, +) + } + + func missingNumber3(_ nums: [Int]) -> Int { + Set(0...nums.count).subtracting(Set(nums)).first! + } + + func missingNumber4(_ nums: [Int]) -> Int { + var answer = 0 + for i in 0 ..< nums.count { + answer = answer ^ i ^ nums[i] + } + + return answer ^ nums.count + } +} diff --git a/missing-number/bhyun-kim.py b/missing-number/bhyun-kim.py new file mode 100644 index 000000000..4276927d2 --- /dev/null +++ b/missing-number/bhyun-kim.py @@ -0,0 +1,29 @@ +""" +268. Missing Number +https://leetcode.com/problems/missing-number/description/ + +Solution: + - Sort the input list + - For each index in the input list: + - If the index is not equal to the element: + - Return the index + - Return the length of the input list + +Time complexity: O(nlogn+n) + - The sort function runs O(nlogn) times + - The for loop runs n times + +Space complexity: O(1) + - No extra space is used +""" +from typing import List + + +class Solution: + def missingNumber(self, nums: List[int]) -> int: + nums.sort() + for i in range(len(nums)): + if i != nums[i]: + return i + + return len(nums) diff --git a/missing-number/invidam.go.md b/missing-number/invidam.go.md new file mode 100644 index 000000000..c6f28a30b --- /dev/null +++ b/missing-number/invidam.go.md @@ -0,0 +1,36 @@ +# Intuition + +배타적인 경우에만 참을 출력하는 `XOR` 연산을 활용한다. +# Approach + +- 문제를 치환해보자. 모든 수가 2번씩 등장하고, 하나의 수만 한 번 등장한다고 하자. +- 이 경우, 모든 수들에 `^`연산을 하면 한 번 등장한 수만을 알 수 있다. +- `배열의 길이` + `인덱스`와 `해당 인덱스일 때의 원소값`들을 모두 `^`연산하면 + - 배열 + 인덱스 순회로 모든 수는 1번씩 등장한다. + - 원소값 순회로 하나의 수를 제외하곤 1번씩 등장한다. +- 한 번만 등장한 수가 missing number이다. +# Complexity +- Time complexity: $$O(n)$$ + +: 배열의 길이 `n`, 이를 순회한다. +- Space complexity: $$O(n)$$ + + : inline, 주어진 배열의 길이 `n` + + +# Code +```go +func missingNumber(nums []int) int { + num := len(nums) + + for i, n := range nums { + num ^= i + num ^= n + } + return num +} +``` + +# Today I Learned +- 다른 풀이로 풀 때, `abs()`를 이용해서 해결하려고 하였는데 해당 라이브러리가 존재하지 않았다. 왜 그런지 찾아봤는데 너무 간단한 라이브러리는 철학에 안맞는다고 안넣어준다 하더라. + - 참고: https://go.dev/doc/faq#x_in_std \ No newline at end of file diff --git a/missing-number/nhistory.js b/missing-number/nhistory.js new file mode 100644 index 000000000..2d25cdf9e --- /dev/null +++ b/missing-number/nhistory.js @@ -0,0 +1,16 @@ +var missingNumber = function (nums) { + // Get a expected summation + const n = nums.length; + const expectedSum = (n * (n + 1)) / 2; + + // Calculate summation of nums + let numsSum = 0; + for (let i = 0; i < n; i++) { + numsSum += nums[i]; + } + + return expectedSum - numsSum; +}; + +// TC: O(n) +// SC: O(1) diff --git a/missing-number/yolophg.js b/missing-number/yolophg.js new file mode 100644 index 000000000..3f7c3799f --- /dev/null +++ b/missing-number/yolophg.js @@ -0,0 +1,13 @@ +// Time Complexity: O(n) +// Space Complexity: O(1) + +var missingNumber = function(nums) { + const n = nums.length; + // sum of numbers from 0 to n. + const expectedSum = (n * (n + 1)) / 2; + // sum of numbers in the array. + const actualSum = nums.reduce((acc, curr) => acc + curr, 0); + + // the difference is the missing number. + return expectedSum - actualSum; +}; diff --git a/number-of-1-bits/Leo.py b/number-of-1-bits/Leo.py new file mode 100644 index 000000000..2675c6b02 --- /dev/null +++ b/number-of-1-bits/Leo.py @@ -0,0 +1,19 @@ +class Solution: + def hammingWeight(self, n: int) -> int: + counter = 0 + + while n: + counter += 1 + n = n & (n - 1) + + return counter + + ## TC: O(k), SC: O(1), since given int(n) has constant length + + # counter = 0 + + # for i in bin(n): + # if i == "1": + # counter += 1 + + # return counter diff --git a/number-of-1-bits/WhiteHyun.swift b/number-of-1-bits/WhiteHyun.swift new file mode 100644 index 000000000..53c06d4d7 --- /dev/null +++ b/number-of-1-bits/WhiteHyun.swift @@ -0,0 +1,24 @@ +// +// 191. Number of 1 Bits +// https://leetcode.com/problems/number-of-1-bits/description/ +// Dale-Study +// +// Created by WhiteHyun on 2024/05/19. +// + +final class Solution { + func hammingWeight(_ n: Int) -> Int { + n.nonzeroBitCount + } + + func hammingWeight2(_ n: Int) -> Int { + var number = n + var answer = 0 + while number != 0 { + answer += number & 1 + number >>= 1 + } + + return answer + } +} diff --git a/number-of-1-bits/bhyun-kim.py b/number-of-1-bits/bhyun-kim.py new file mode 100644 index 000000000..64f7f3e0c --- /dev/null +++ b/number-of-1-bits/bhyun-kim.py @@ -0,0 +1,31 @@ +""" +191. Number of 1 Bits +https://leetcode.com/problems/number-of-1-bits/ + +Solution: + - Create a counter + - For each bit in the input number: + - If the bit is 1: + - Increment the counter + - Return the counter + +Time complexity: O(1) + - The while loop runs 32 times + +Space complexity: O(1) + - No extra space is used +""" + + +class Solution: + def hammingWeight(self, n: int) -> int: + output = 0 + + i = 1 << 31 + while i > 0: + if (n & i) != 0: + output += 1 + + i = i >> 1 + + return output diff --git a/number-of-1-bits/invidam.go.md b/number-of-1-bits/invidam.go.md new file mode 100644 index 000000000..86ea04908 --- /dev/null +++ b/number-of-1-bits/invidam.go.md @@ -0,0 +1,29 @@ +# Intuition +비트 연산자를 활용하여 계산한다. +# Approach +1. `n`과 비교하기 위한 `mask`를 생성한다. +2. `mask`를 2진수 `1`, `10`, `100` 순으로 증가시킨 후 `&` 연산자를 활용해, n의 특정 비트가 `1`인지 판단한다. +3. 참인 경우 `cnt`를 증가시켜 결과를 구한다. + +# Complexity +- Time complexity: $$O(logn)$$ + +: `mask`가 있는 반복문에 의해 결정된다. `mask`는 입력으로 들어온 `n`까지 2배씩 증가하므로 $$O(logn)$$이다. +- Space complexity: $$O(1)$$ + +: 별도 자료구조를 사용하지 않는다. +# Code +```go +func hammingWeight(n int) int { + cnt := 0 + for mask := 1; mask <= n; mask = mask << 1 { + if (mask & n) != 0 { + cnt += 1 + } + } + return cnt +} +``` + +# What I learned +- 고언어에서 첫 비트 연산자 활용 \ No newline at end of file diff --git a/number-of-1-bits/nhistory.js b/number-of-1-bits/nhistory.js new file mode 100644 index 000000000..4a14ccfb9 --- /dev/null +++ b/number-of-1-bits/nhistory.js @@ -0,0 +1,13 @@ +var hammingWeight = function (n) { + let count = 0; + while (n) { + // Check rightmost bit is equal to 1 by using bitwise AND operator + count += n & 1; + // Remove rightmost bit from n by using right shift operator + n >>= 1; + } + return count; +}; + +// TC: O(1) -> The worst case of 32-integer would be O(32) +// SC: O(1) diff --git a/number-of-1-bits/yolophg.js b/number-of-1-bits/yolophg.js new file mode 100644 index 000000000..cf00076d5 --- /dev/null +++ b/number-of-1-bits/yolophg.js @@ -0,0 +1,14 @@ +// Time Complexity: O(log n) +// Space Complexity: O(1) + +var hammingWeight = function(n) { + let count = 0; + while (n !== 0) { + // add 1 to count if the last bit is 1. + count += n & 1; + // unsigned right shift to process the next bit. + n = n >>> 1; + } + + return count; +}; diff --git a/reverse-bits/Leo.py b/reverse-bits/Leo.py new file mode 100644 index 000000000..3fca085cc --- /dev/null +++ b/reverse-bits/Leo.py @@ -0,0 +1,16 @@ +class Solution: + def reverseBits(self, n: int) -> int: + + res = 0 + + for i in range(32): + if n & 1: + res += 1 << (31 - i) + n >>= 1 + + return res + + # TC: O(1), SC: O(1) for both codes + + # n = bin(n)[2:].zfill(32) + # return int(n[::-1], 2) diff --git a/reverse-bits/WhiteHyun.swift b/reverse-bits/WhiteHyun.swift new file mode 100644 index 000000000..768b3db93 --- /dev/null +++ b/reverse-bits/WhiteHyun.swift @@ -0,0 +1,28 @@ +// +// 190. Reverse Bits +// https://leetcode.com/problems/reverse-bits/description/ +// Dale-Study +// +// Created by WhiteHyun on 2024/05/19. +// + +final class Solution { + + // MARK: - Runtime: 5ms / Memory 16.12 MB + + func reverseBits(_ n: Int) -> Int { + let reversedStringBits = String(String(n, radix: 2).reversed()) + return Int(reversedStringBits + String(repeating: "0", count: 32 - reversedStringBits.count), radix: 2)! + } + + // MARK: - Runtime: 5ms / Memory 15.72 MB + + func reverseBits2(_ n: Int) -> Int { + var answer = 0 + + for index in 0 ..< 32 { + answer += ((n >> (32 - index - 1)) & 1) << index + } + return answer + } +} diff --git a/reverse-bits/bhyun-kim.py b/reverse-bits/bhyun-kim.py new file mode 100644 index 000000000..66c709a0d --- /dev/null +++ b/reverse-bits/bhyun-kim.py @@ -0,0 +1,26 @@ +""" +190. Reverse Bits +https://leetcode.com/problems/reverse-bits/description/ + +Solution: + - Convert the number to binary string + - Reverse the binary string + - Convert the reversed binary string to integer + - Return the integer + +Time complexity: O(1) + - The bin function runs once + - The reversed function runs once + - The int function runs once + +Space complexity: O(1) + - No extra space is used + +""" + + +class Solution: + def reverseBits(self, n: int) -> int: + n_bin = bin(n)[2:].zfill(32) + n_bin = "".join(reversed(n_bin)) + return int(n_bin, base=2) diff --git a/reverse-bits/nhistory.js b/reverse-bits/nhistory.js new file mode 100644 index 000000000..2bf73f1fc --- /dev/null +++ b/reverse-bits/nhistory.js @@ -0,0 +1,16 @@ +var reverseBits = function (n) { + // Make variable to store input + // toString method doesn't include 0 front of number + let binary = n.toString(2); + + // Added number of 0s to satisfy 32 bits + while (binary.length < 32) { + binary = "0" + binary; + } + + // Reversed binary string and convert into integer + return parseInt(binary.split("").reverse().join(""), 2); +}; + +// TC: O(1) +// SC: O(1) diff --git a/reverse-bits/yolophg.js b/reverse-bits/yolophg.js new file mode 100644 index 000000000..283a9b0b0 --- /dev/null +++ b/reverse-bits/yolophg.js @@ -0,0 +1,16 @@ +// Time Complexity: O(1) +// Space Complexity: O(1) + +var reverseBits = function(n) { + let result = 0; + // iterate 32 times since it's a 32-bit integer. + for (let i = 0; i < 32; i++) { + // shift the result to the left by 1 bit and OR it with the least significant bit of n. + result = (result << 1) | (n & 1); + // right shift n by 1 to consider the next bit. + n >>>= 1; + } + + // convert to unsigned integer. + return result >>> 0; +};