Skip to content

[b41-41] Week 03 solutions #1303

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 19, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions number-of-1-bits/b41-41.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
function hammingWeight(n: number): number {

// 풀이 1:
// binary로 변환 후 1 count
// 시간 복잡도: O(log n)
// 공간 복잡도: O(log n)
const getResult1 = () => {
const binaryNum = n.toString(2);

let count = 0;

for(let i = 0; i < binaryNum.length; i++) {
if(binaryNum.charAt(i) === '1') {
count++
}
}

return count;
};

// 풀이 2:
// 비트 연산을 활용할 수 있다고 함 (From GPT)
// 시간 복잡도: O(log n)
// 공간 복잡도: O(1)
// const getResult2 = () => {
// let count = 0;

// while (n !== 0) {
// count += n & 1;
// n >>>= 1;
// }

// return count;
// }
Comment on lines +21 to +34
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

비트 연산을 활용하면 공간 복잡도 측면에서 훨씬 유리하군요!


return getResult1();
// return getResult2();
};
23 changes: 23 additions & 0 deletions valid-palindrome/b41-41.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
function isPalindrome(s: string): boolean {

// 풀이 1:
// lowcase 변환, 졍규식으로 문자 이외 필터
// 필터된 문자열 순회하면서 (i, length - i)
// 전부 일치하면 true 아니면 false
// 시간 복잡도: O(n)
// 공간 복잡도: O(n)

const validPalindrome1 = () => {
const sanitizedStrArr = [...s.toLowerCase().replace(/[^a-z0-9]/g, "")];

for(let i = 0; i < Math.floor(sanitizedStrArr.length / 2); i++) {
if(sanitizedStrArr[i] !== sanitizedStrArr[(sanitizedStrArr.length - 1) - i]) {
return false;
}
}

return true;
}

return validPalindrome1();
};