본문 바로가기

Algorithm

[LeetCode] Plus One (ChatGPT코드)

문제 

You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's. Increment the large integer by one and return the resulting array of digits.

 

오답 노트

/**
 * @param {number[]} digits
 * @return {number[]}
 */
var plusOne = function(digits) {
     const digitToString = digits.join()   ;
     let num = Number(digitToString.replaceAll(',',''));
     num = num + 1;
     num = num.toString();
     num = num.split('');
    
    return num 
};

 

분명 문제가 없을거라고 생각했는데. 숫자가 커지니 output에 문제가 발생했다. 정확한 진단을 위해 chatGpt에게 물어보았고. 내가 작성한 코드에 3가지 문제점이 있다는 피드백을 받았다. 


1. 숫자 배열을 문자열로 변환한 다음 다시 숫자로 파싱하여 더하는 방식으로는 숫자가 너무 큰 경우 정밀도 문제가 발생할 수 있다.

2. 예상 출력인 정수 배열 대신 문자 배열을 반환한다.

3. 번호에 하나를 추가할 때 캐리를 올바르게 처리하지 않는다. 


Chat GPT 코드

var plusOne = function(digits) {
    const n = digits.length;
    let carry = 1; // Initialize carry to 1 to add one to the number.

    for (let i = n - 1; i >= 0; i--) {
        const sum = digits[i] + carry;

        if (sum >= 10) {
            digits[i] = sum % 10; // Set the current digit.
            carry = 1; // Update the carry.
        } else {
            digits[i] = sum; // Set the current digit.
            carry = 0; // Reset the carry if no carry is needed.
            break; // No need to continue if there's no carry.
        }
    }

    if (carry === 1) {
        digits.unshift(1); // Add an additional digit if carry is still 1.
    }

    return digits;
};

정수로 바꿀게 아니라, 배열 내에서 순회하며 더해주는 방법이 있었다!