-
Notifications
You must be signed in to change notification settings - Fork 126
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
Evan, Week 4 #85
Evan, Week 4 #85
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
엄청 빨리 푸셨군요 ㅎㅎ 고생하셨습니다!
/** | ||
* Time Complexity: O(1) | ||
* Reason: | ||
* - n.toString(2): Converts the number to a binary string, which has a fixed length of up to 32 bits. This is O(1) because the length is constant. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Not sure if this built-in function would take a constant amount of time regardless of the input size. 🤔
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for feedback
Hmm... I thought this way because input size is fixed with 32 bits.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The processing speed will vary depending on the number given, but no matter how large the number gets, 32 bits is the maximum, so it's a constant time in terms of time complexity. Of course, constant time complexity doesn't mean it's efficient.
If you don't think so, can you give me your example?
var countBits = function (n) { | ||
const result = new Array(n + 1).fill(0); | ||
|
||
for (let i = 1; i <= n; i++) { | ||
/** The number of 1's in i divided by 2, except last bit of i */ | ||
const totalOnes = result[i >> 1]; | ||
const lastBit = i & 1; | ||
|
||
result[i] = totalOnes + lastBit; | ||
} | ||
|
||
return result; | ||
}; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What an elegant solution! 🏅
var hammingWeight = function (n) { | ||
return n.toString(2).replace(/0/g, "").length; | ||
}; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
JS를 모르는 저로써는 꽤나 신기한 코드네요 ㅎㅎ
toString(2)가 2진수로 변환하는 거고, replace(/0/g, "")
는 Regex로 0을 찾아서 빈 문자열로 변환하는 코드로 이해했는데 맞을까요?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
맞습니다!
이진수 연산을 도와주는 편한 메서드가 많이 있네요ㅎㅎ
No description provided.