-
Notifications
You must be signed in to change notification settings - Fork 0
/
989_add_to_array_form_of_integer.rb
76 lines (63 loc) · 1.08 KB
/
989_add_to_array_form_of_integer.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# frozen_string_literal: true
# https://leetcode.com/problems/add-to-array-form-of-integer/
# @param {Integer[]} num
# @param {Integer} k
# @return {Integer[]}
def add_to_array_form(num, k)
result = []
k_l = (::Math.log10(k) + 1).to_i
p = 0
add = 0
n = num.length
while p < k_l && p < n
k_num = k % 10
n_num = num[n - p - 1]
sum = k_num + n_num
if sum > 9
sum += add
sum -= 10
add = 1
elsif add != 0
sum += add
if sum < 10
add = 0
else
sum = 0
end
end
result << sum
k /= 10
p += 1
end
if k_l > p
(p...k_l).each do |_i|
j = k % 10
k /= 10
unless add.zero?
j += add
if j > 9
j -= 10
else
add = 0
end
end
result << j
end
end
if p < n
((p + 1)..n).each do |i|
j = num[n - i]
unless add.zero?
j += add
if j > 9
j -= 10
else
add = 0
end
end
result << j
end
end
result << 1 unless add.zero?
result.reverse
end