티스토리 뷰
We define S to be a sequence of distinct sequential integers from 1 to n; in other words, S = {1, 2, 3,..., n}. We want to know the maximum bitwise AND value of any two integers, a and b (where a < b), in sequence S that is also less than a given integer, k.
Complete the function in the editor so that given n and k, it returns the maximum a & b < k.
Note: The & symbol represents the bitwise AND operator.
풀이 → Failed
function getMaxLessThanK(n, k) {
let seq = [];
for(let i = 1; i < n; i++) {
for(let j = 2; j <= n; j++) {
let bitAnd = parseInt(i & j);
let toDecimal = parseInt(bitAnd, 10)
if(toDecimal < k) seq.push(toDecimal);
}
}
return Math.max.apply(null, seq);
}
Test case 6개 중에 4개는 실패.
input이 너무 많으면 감당하지 못해 에러발생 → 실패하는 것으로 보임.
개선한 풀이
function getMaxLessThanK(n, k) {
let max = 0;
for(let i = 1; i < n; i++) {
for(let j = 2; j <= n; j++) {
if(i < j && i != j) {
let bitAnd = parseInt(i & j);
let toDecimal = parseInt(bitAnd, 10)
if(toDecimal < k) {
if(toDecimal > max) max = toDecimal;
}
}
}
}
return max;
}
max라는 변수를 만들어서, k보다 작은 결과값들을 비교해주고, 제일 큰 값이면 max에 넣어줌으로써 문제 해결! (짝짝짝👏🏻)
애초에 req는 필요없었네!
다른 사람의 풀이
function getMaxLessThanK(n, k) {
let max_anb = 0;
for (let b = n; b > 0; b--) {
for (let a = b-1; a > 0; a--) {
if ((a & b) < k && (a & b) > max_anb){
max_anb = (a&b);
}
}
}
return max_anb;
}
훨씬 간결하다! 그리고 안에 있는 for문에서 b보다 항상 1 작은 값으로 a를 처리해서 불필요한 if문 하나를 더 줄였구나🧐
아니 근데.. 굳이 2진법으로 변환하지 않아도 비트연산자가 되는구나(머쓱)
'1Day 1Algorithm' 카테고리의 다른 글
[DAY 6] Recursion: Fibonacci Numbers (0) | 2019.10.06 |
---|---|
[DAY 5] Flipping bits (0) | 2019.10.05 |
[DAY 3] Compare the Triplets (0) | 2019.10.03 |
[DAY 2] Simple Array Sum (0) | 2019.10.02 |
[DAY 1] Sock Merchant (0) | 2019.10.01 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 웹팩
- greedyAlgorithm
- Webpack
- 운영체제
- 알고리즘
- sort
- 시분할시스템
- Typescript
- 컴퓨터공학
- 프로그래머스
- 자바스크립트
- reduce()
- 1day1algorithm
- 타입스크립트
- React
- javascript
- Array
- 배치처리시스템
- 우아한테크러닝
- 멀티프로그래밍
- 리액트
- Props
- js
- 구간합
- 배열
- OS
- Algorithm
- 자료구조
- redux-saga
- sort()
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
글 보관함