[LeetCode] 273. Integer to English Words

Chobby·2025년 2월 28일
1

LeetCode

목록 보기
265/427

😎풀이

  1. 1부터 19까지 정의
  2. 20부터 90까지 정의
  3. 천, 백만, 십억 정의
  4. num이 0 이상으로 표현할 수 있는 수 일 동안 반복
    4-1. num을 천으로 나누었을 때 나머지가 있어 정의해야 할 경우 정의
    4-2. num을 1000으로 나눈 몫을 num에 할당
    4-3. i를 증가시켜 천, 백만, 십억에 대해 정의
  5. helper함수 정의
    5-1. 변수가 발생하는 0일 때, 20미만일 때, 100 미만일 때를 계산하여 상황에 맞게 반환
const belowTwenty: string[] = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"];
const tens: string[] = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"];

function numberToWords(num: number): string {
    if (num === 0) return "Zero";
    
    const thousands: string[] = ["", "Thousand", "Million", "Billion"];
    
    let res = "";
    let i = 0;
    
    while (num > 0) {
        if (num % 1000 !== 0) {
            res = helper(num % 1000) + thousands[i] + " " + res;
        }
        num = Math.floor(num / 1000);
        i++;
    }
    
    return res.trim();
}

function helper(num: number): string {
    if (num === 0) return "";
    else if (num < 20) return belowTwenty[num] + " ";
    else if (num < 100) return tens[Math.floor(num / 10)] + " " + helper(num % 10);
    else return belowTwenty[Math.floor(num / 100)] + " Hundred " + helper(num % 100);
}
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글