728x90

백준 1110번: 더하기 사이클 (https://www.acmicpc.net/problem/1110)

 

Code

const fs = require('fs');
let newNum = fs.readFileSync('/dev/stdin').toString();
const ORIGIN = parseInt(newNum);
let counter = 0;
 
while (newNum !== ORIGIN || counter === 0) {
newNum = (newNum % 10) * 10 + ((parseInt(newNum / 10) + (newNum % 10)) % 10);
counter++;
}
 
console.log(counter);
 
// Timeout code (시간 초과 코드)
 
// const fs = require('fs');
// let input = fs.readFileSync('/dev/stdin').toString();
 
// if (parseInt(input) < 10) {
// input = '0' + input;
// }
 
// let newNum = input;
// let counter = 0;
// let sum = 0;
 
// while (newNum !== input || counter === 0) {
// sum = parseInt(newNum[0]) + parseInt(newNum[1]);
 
// if (sum < 10) {
// sum = '0' + sum.toString();
// } else {
// sum = sum.toString();
// }
 
// newNum = newNum[1] + sum[1];
// counter++;
// }
 
// console.log(counter);

😢 너무 순진하게 문제 그대로를 코드로 작성하려 하다보니, 코드가 길어져 시간 초과가 발생하였다.

😊'10의 자릿수'와 '1의 자릿수'를 구하는 방법만 알면 쉽게 해결할 수 있다.

10의 자릿수 : (newNum%10)*10

✔ 1의 자릿수 : ( parseInt( newNum/10 ) + ( newNum%10 ) ) % 10

1️⃣초기값(===새로운 수)2️⃣ 각 자릿수 더하기 3️⃣ 새로운 수
26 👉 2+6=08 👉 68
68 👉 6+8=14 👉 84
84 👉 8+4=12 👉42
42 👉 4+2=06 👉26
2️⃣식에서 각 자릿수를 더할 때 '1의 자릿수'를 '10의 자릿수'로 만들어 주기 위해 ' 10의 자릿수'식 사용
2️⃣식에서 각 자릿수를 더한 결과값의 '1의 자릿수'를 구하기 위해 ' 1의 자릿수'식 사용
위의 두 값을 합하면 '새로운 수'를 구할 수 있다. (반복)

+ Recent posts