JavaScript solution using reduceRight O(n)


  • 0
    S
    function plusOne(digits) {
      return digits.reduceRight((acc, digit, index) => {
        const rawValue = digit + (acc.carryOver ? 1 : 0) + (index === digits.length - 1 ? 1 : 0);
        const finalValue = rawValue % 10;
    
        acc.carryOver = finalValue !== rawValue;
        acc.result.unshift(finalValue);
    
        if (index === 0 && acc.carryOver) {
          acc.result.unshift(1);
        }
    
        return acc;
      }, {
        result: [],
        carryOver: false
      }).result;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.