[알고리즘] 백준 25495 에어팟 (자바스크립트)

Subin·2022년 12월 9일
0
post-thumbnail

시뮬레이션
에어팟

✏️ 요구 사항 분석

입력

  1. 에어팟에 핸드폰을 연결한 횟수 N
  2. 핸드폰 종류는 1~9의 숫자 A

출력

  1. 현재 에어팟의 배터리 소모량을 출력

배터리를 소모하는 경우

  1. 새로운 핸드폰에 연결시 기존 핸드폰과 연결 끊기고, 배터리 2퍼센트 소모
  2. 이미 연결 된 핸드폰에 다시 연결시, 직전 배터리 소모량의 2배 만큼 배터리 소모

누적 배터리 소모량이 100퍼센트 이상시

  1. 누적 배터리 소모량 100퍼센트 이상이 될 시 연결 해제, 배터리 소모량 0
  2. 배터리 소모량이 100퍼센트 이상시 다음 핸드폰 부터는 새로운 에어팟에 연결

🗒 내 풀이

function solution(string) {
  const input = string.split("\n");
  const N = input[0];
  const A = input[1].split(" ");
  const drain = 2;
  let currentPhone = 0;
  let battery = 0;
  let currentBattery = 0;
  for (let i = 0; i < N; i++) {
    if (A[i] !== currentPhone) {
      battery += drain;
      currentBattery = drain;
    } else {
      battery += currentBattery * 2;
      currentBattery *= 2;
    }
    currentPhone = A[i];
    if (battery >= 100) {
      battery = 0;
      currentPhone = 0;
      currentBattery = 0;
    }
  }
  return battery;
}
const string = `7
2 2 2 2 2 2 2`;
console.log(solution(string));

⌨️ 풀이 과정

1

if (A[i] !== currentPhone) {
  battery += drain;
  currentBattery = drain;
} else {
  battery += currentBattery * 2;
  currentBattery *= 2;
}

이전 폰과 새로운 폰이 다르면 새로운 폰으로 바뀐 것이니 배터리 2퍼 소모 및 2퍼 소모 누적
그게 아니면 직전 배터리 소모량의 2배 소모, 전 배터리 소모량의 2배 소모 누적

2

if (battery >= 100) {
  battery = 0;
  currentPhone = 0;
  currentBattery = 0;
}

누적 배터리 소모량 100퍼센트 이상이 될 시 배터리 0으로 초기화 , 누적 배터리 0 초기화, 핸드폰 연결 해제

profile
고양이가 세상을 지배한다.

0개의 댓글