안녕하세요.
이어서 정답률 66% 문제를 풀어보겠습니다.
function solution(a, b) {
while(1){
if(a%2 === 0){
a/=2;
}
else if(a%5 === 0){
a/=5;
}
if(b%2 === 0){
b/=2;
}
else if(b%5 === 0){
b/=5;
}
if(a%2 !==0 && a%5 !== 0 && b%2 !==0 && b%5 !== 0){
break;
}
}
return b === 1 || b/a === 1 || Number.isInteger(a/b)?1:2;
//분자가 분모보다 큰 경우도 포함.
}
function solution(chicken) {
var answer = 0;
let sum = 0;
let rest = 0;
while(chicken >= 10){
answer = chicken - chicken%10;
rest += chicken%10;
chicken = answer/10;
if(rest >= 10){
rest = rest%10;
chicken+=10;
}
sum += answer;
}
sum += rest+chicken;
return Math.floor(sum/10);
}
(추가!!)
function solution(chicken) {
return parseInt((chicken-1)/9);
}
등비수열의 합을 이용하면 위의 식과 같이 나올 수 있다.
치킨 열마리당 쿠폰 하나, 쿠폰 열개 당 치킨 한마리는 치킨 한마리를 시켜먹으면 1+1/10을 먹는것과 같다.
치킨 a마리를 먹으면 총 먹을 수 있는 치킨의 갯수는 a + a×1/10+a1/10×1/10+a×1/10×1/10×1/10+...... 무한대이다.
무한등비급수의 합 공식을 떠올려보면 a/1-r이다. a:초항,r:공비
따라서
입출력 예제 chicken = 1081, result = 120을 이용해 풀이를 하면
a = 1081, 1081/1-1/10 = 1081×10/9 = 1201.111111..로 총 먹을수 있는 치킨의 양이다.
받을 수 있는 최대 서비스 치킨의 수를 return하라 했으므로 1201.111-1081을 내림한 120이 되는것이다.
이때 공식은
function solution(chicken) {
return parseInt((chicken)/9);
}
으로 추정된다.
하지만 주의할점은 9의 배수에서 문제가 생긴다.
치킨을 9마리 먹었다고 생각해보자. 쿠폰이 10개가 모이지 않았지만 공식에 적용하면 공짜 치킨이 생겨버린다.
이는 18마리, 27마리 ... 를 대입해봐도 결과가 똑같다.
따라서 치킨에 한마리를 시켰을 때 주는 쿠폰수인 1을 빼주게되면 숫자가 한칸씩 앞으로 당겨지게 되어 문제가 해결된다.
function solution(score) {
let answer = score.map(x => (x[1]+x[0])/2);
score = score.map(x => (x[1]+x[0])/2).sort((a,b)=>b-a);
return answer.map(x=> score.indexOf(x)+1);
}
(추가!!)
function solution(score) {
return score.map(el => {
return score.filter(x => x[0]+x[1]>el[0]+el[1]).length+1;
});
}
function solution(numlist, n) {
let l = 0;
numlist = numlist.map(x=>x-n).sort((a,b)=>(Math.abs(a)-Math.abs(b)));
for(let i = 0; i < numlist.length-1 ; i++){
if(Math.abs(numlist[i])===Math.abs(numlist[i+1])){
if(numlist[i] < numlist[i+1]){
l = numlist[i];
numlist[i] = numlist[i+1];
numlist[i+1] = l;
}
}
}
return numlist.map(x => x+n);
}
(추가!!)
function solution(numlist, n) {
return numlist.sort((a,b) => Math.abs(a-n)-Math.abs(b-n)||b-a);
}
//n을 기준으로 오름차순 정렬이지만 n과의 거리가 같을때 0이므로 ||를 통해 b-a인 내림차순으로 정렬한다.