fork download
  1. /*
  2. 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.
  3.  
  4. Increment the large integer by one and return the resulting array of digits.
  5.  
  6.  
  7.  
  8. Example 1:
  9.  
  10. Input: digits = [1,2,3]
  11. Output: [1,2,4]
  12. Explanation: The array represents the integer 123.
  13. Incrementing by one gives 123 + 1 = 124.
  14. Thus, the result should be [1,2,4].
  15. Example 2:
  16.  
  17. Input: digits = [4,3,2,1]
  18. Output: [4,3,2,2]
  19. Explanation: The array represents the integer 4321.
  20. Incrementing by one gives 4321 + 1 = 4322.
  21. Thus, the result should be [4,3,2,2].
  22. Example 3:
  23.  
  24. Input: digits = [9]
  25. Output: [1,0]
  26. Explanation: The array represents the integer 9.
  27. Incrementing by one gives 9 + 1 = 10.
  28. Thus, the result should be [1,0].
  29.  
  30.  
  31. Constraints:
  32.  
  33. 1. 1 <= digits.length <= 100
  34. 2. 0 <= digits[i] <= 9
  35. 3. digits does not contain any leading 0's.
  36.  
  37. */
  38.  
  39.  
  40.  
  41. function increareArrayDigitByOne(arr){
  42.  
  43. let remainder=1;
  44.  
  45. for(let a=arr.length-1;a>=0;a--){
  46. let digitWithRemainder=arr[a]+remainder;
  47.  
  48. if(digitWithRemainder===10&&a!==0){
  49. arr[a]=0;
  50. remainder=1;
  51. }else if(digitWithRemainder===10&&a===0){
  52. arr[a]=1;
  53. arr.push(0);
  54. }else{
  55. arr[a]=digitWithRemainder;
  56. remainder=0;
  57. return;
  58. }
  59.  
  60. }
  61. console.log(arr);
  62. return arr;
  63.  
  64. }
  65.  
  66. increareArrayDigitByOne([9,9,9])
  67.  
  68.  
Success #stdin #stdout 0.04s 41340KB
stdin
Standard input is empty
stdout
[ 1, 0, 0, 0 ]