Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2017
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. Given a non-negative number represented as an array of digits,
  2.  
  3. add 1 to the number ( increment the number represented by the digits ).
  4.  
  5. The digits are stored such that the most significant digit is at the head of the list. There can be upto 10,000 digits in the input array.
  6.  
  7. Example:
  8.  
  9. If the vector has [1, 2, 3]
  10.  
  11. the returned vector should be [1, 2, 4]
  12.  
  13. as 123 + 1 = 124.
  14.  
  15. def plusOne(a)
  16. new_number = a.join.to_i + 1
  17. result = []
  18. while new_number > 0
  19. result.push new_number%10
  20. new_number /= 10
  21. end
  22. result.reverse
  23. end
  24.  
  25. def plusOne(a)
  26. carry = 1
  27. start_index = a.size - 1
  28. temp_result = []
  29. ans = []
  30.  
  31. for i in start_index.downto(0)
  32. sum = a[i] + carry
  33. carry = sum/10
  34. temp_result.push sum%10
  35. end
  36. temp_result.push carry
  37.  
  38. start_index = temp_result.size - 1
  39. while start_index >= 0 and temp_result[start_index] == 0
  40. start_index -= 1
  41. end
  42.  
  43. while start_index >= 0
  44. ans.push temp_result[start_index]
  45. start_index -= 1
  46. end
  47. ans
  48. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement