쉽게 구한다면 while(n>1) { n/=2; count++} 이런식으로 구할 수 있겠지만 곱하기(*) 나누기(/) 연산은 생각보다 엄청나게 느리다.
보통 더하기 연산의 수십배 이상 느린 곱하기, 나누기 연산이라고 했을 때.... 그래서 아래와 같이 바꿀 수 있는데
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class LogUtil { | |
static int log2 (int number) { | |
int logCount = 0; | |
if(65536 <= number) { logCount += 16; number >>= 16; } | |
if(256 <= number) { logCount += 8; number >>= 8; } | |
if(16 <= number) { logCount += 4; number >>= 4; } | |
if(4 <= number) { logCount += 2; number >>= 2; } | |
return logCount + (2 <= number ? 1 : 0); | |
} | |
} |
뭔가 좀더 줄이고 싶다면 logBitCount 만에 구할 수 있다. 탐색문제나 log2로 무엇인가 구해야하는 문제가 나왔다면 곤란하기 짝이 없는데 아래와 같은 코드로 생각보다 쉽게 구할 수 있다(물론 정수 값만 가능하다.)
'알고리즘' 카테고리의 다른 글
[Algorithm/Tree] Binary Tree (이진트리) (0) | 2017.01.03 |
---|---|
[Algorithm/boj] 애너그램 그룹 (0) | 2017.01.01 |
[Algorithm/boj] 애너그램 만들기 (0) | 2017.01.01 |
[Algorithm/boj] 애너그램 거리(anagram distance) (0) | 2017.01.01 |
[BOJ/SegmentTree] 최소값 최대값 (0) | 2016.12.30 |