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;
}

// 처음 풀었던 풀이.
// unsigned int answer = 0;
// for (int i = 0; i < 32; i++) {
// if ((n >> i) & 1) answer++;
// }

// 생각 못 한 풀이
// -> 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;
left++;
right--;
}
}

return true;
}
};
#pragma endregion
Loading