Skip to content
Open
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
51 changes: 51 additions & 0 deletions number-of-1-bits/OstenHun.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
191. Number of 1 Bits

Given a positive integer n, write a function
that returns the number of set bits in its binary representation
(also known as the Hamming weight).

Example 1:
Input: n = 11
Output: 3

Explanation:
The input binary string 1011 has a total of three set bits.

Constraints:
1 <= n <= 2^31 - 1
*/

// 비트 연산을 이용하여 풀기
#include <iostream>
using namespace std;

// 시간 복잡도 : O(logn) -> n >> 1 연산을 하기 때문에 절반씩 줄어듬
// 문제의 조건은 32bit 내의 범위이기 때문에 32번의 반복으로 항상 끝나기에 O(1)이라고 할 수 있다.
// 공간 복잡도 : O(1)
class Solution {
public:
int hammingweight(int n) {
unsigned int answer = 0;
while(n>0) {
if (n & 1)
answer++;
n = n >> 1;
}
Comment on lines +29 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.

요 부분의 깔끔함이 눈길을 끄는건 부정할 수 없네요.

Copy link
Member Author

Choose a reason for hiding this comment

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

동의합니다.. 정말 깔끔한 거 같아요.
32번보다 적게 확인하는 법이 없을까? 하다가 작성하게 됐네요

저에게 큰 충격을 준건 마지막 풀이였네요. 제가 생각한 건 아니고 AI와 대화 하다 보니 알게 된 풀이인데
정말 멋진 풀이 같습니다


// 처음 풀었던 풀이.
// unsigned int answer = 0;
// for (int i = 0; i < 32; i++) {
// if ((n >> i) & 1) answer++;
// }
Comment on lines +37 to +40
Copy link
Contributor

Choose a reason for hiding this comment

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

가독성은 이 쪽이 더 좋은 것 같기는 한데,


// 생각 못 한 풀이
// -> n & (n-1) 을 하면 가장 오른쪽 1비트를 지운다.
// while (n > 0) {
// n &= (n - 1);
// answer++;
// }

return answer;
}
};
84 changes: 84 additions & 0 deletions valid-palindrome/OstenHun.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/*
A phrase is a palindrome if,
after converting all uppercase letters into lowercase letters and
removing all non-alphanumeric characters, it reads the same forward and backward.
Alphanumeric characters include letters and numbers.

Given a string s, return true if it is a palindrome, or false otherwise.

Example 1:

Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.

Constraints:

1 <= s.length <= 2 * 105
s consists only of printable ASCII characters.
*/

#include <cctype>
#include <string>
#include <vector>
using namespace std;

#pragma region ExtraSpaceIdea
// 새로운 배열을 만들어서 문자열을 정리한 후에 팰린드롬 판별
// 시간 복잡도 : O(n)
// 공간 복잡도 : O(n)
// n은 문자열의 길이일 것이다.
namespace extra_space_idea {

class Solution {
public:
bool isPalindrome(string s) {
vector<char> str;
str.reserve(s.size());

size_t len = s.length();
for (size_t i = 0; i < len; i++) {
if (isalnum(s[i])) {
str.push_back(tolower(s[i]));
}
}

size_t vec_len = str.size();
for (size_t i = 0; i < (vec_len + 1) / 2; i++) {
if (str[i] != str[vec_len - 1 - i]) return false;
}

return true;
}
};

} // namespace extra_space_idea
#pragma endregion

#pragma region FinalSolution
// 투 포인터를 이용해 추가 배열 없이 구현
// 시간 복잡도 : O(n)
// 공간 복잡도 : O(1)
class Solution {
public:
bool isPalindrome(string s) {
int left = 0;
int right = s.length() - 1;

while(left < right) {
if (!isalnum(s[left]))
left++;
else if (!isalnum(s[right]))
right--;
else {
if (tolower(s[left]) != tolower(s[right]))
return false;
Comment on lines +74 to +75
Copy link
Contributor

Choose a reason for hiding this comment

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

Number of 1 Bits 문제의 여러 해답을 제출하신 걸 보니... 혹시 비트 트릭을 좋아하시나요? 👀 그렇다면 이미 아실 것 같지만, ASCII 코드에서 A65이고 a9732만큼 차이나는 것을 이용하여 비트 연산 한 번으로 대소문자 변환을 구현하는 방법이 있습니다. 물론, 숫자 입력에는 써먹을 수 없어서 이 문제에서는 std::tolower를 써야하지만 이런 부분에 흥미를 느끼실 것 같아 남겨봅니다 :)

Copy link
Member Author

Choose a reason for hiding this comment

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

이전에 배웠다는 기억은 있으나 기억의 저편에 있던 내용이네요 ㅎㅎ; 비트 연산은 언제 봐도 정말 멋진 거 같아요
리뷰 정말 감사합니다. 정말 많은 도움이 되네요! 영상도 잘 봤습니다!!

left++;
right--;
}
}

return true;
}
};
#pragma endregion
Loading