Skip to content

Commit 56731e8

Browse files
committed
Create: 0989-add-to-array-form-of-integer
1 parent ee7a3bc commit 56731e8

4 files changed

+104
-0
lines changed
+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package main
2+
3+
func main() {
4+
5+
}
6+
7+
func addToArrayForm(num []int, k int) []int {
8+
// Reverse
9+
for i, j := 0, len(num)-1; i < j; i, j = i+1, j-1 {
10+
num[i], num[j] = num[j], num[i]
11+
}
12+
i := 0
13+
14+
for k > 0 {
15+
digit := k % 10
16+
17+
if i < len(num) {
18+
num[i] += digit
19+
} else {
20+
num = append(num, digit)
21+
}
22+
23+
carry := num[i] / 10
24+
num[i] %= 10
25+
26+
k /= 10
27+
k += carry
28+
i++
29+
}
30+
31+
// Reverse
32+
for i2, j := 0, len(num)-1; i2 < j; i2, j = i2+1, j-1 {
33+
num[i2], num[j] = num[j], num[i2]
34+
}
35+
36+
return num
37+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* @param {number[]} num
3+
* @param {number} k
4+
* @return {number[]}
5+
*/
6+
var addToArrayForm = function (num, k) {
7+
num.reverse();
8+
let i = 0;
9+
10+
while (k > 0) {
11+
const digit = k % 10;
12+
i < num.length ? (num[i] += digit) : num.push(digit);
13+
14+
const carry = Math.floor(num[i] / 10);
15+
num[i] %= 10;
16+
17+
k = Math.floor(k / 10);
18+
k += carry;
19+
i++;
20+
}
21+
22+
return num.reverse();
23+
};
+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
impl Solution {
2+
pub fn add_to_array_form(num: Vec<i32>, k: i32) -> Vec<i32> {
3+
let mut num: Vec<i32> = num.into_iter().rev().collect();
4+
let mut k = k;
5+
let mut i = 0;
6+
7+
while k > 0 {
8+
let digit = k % 10;
9+
10+
if i < num.len() {
11+
num[i] += digit;
12+
} else {
13+
num.push(digit);
14+
}
15+
16+
let carry = num[i] / 10;
17+
num[i] = num[i] % 10;
18+
19+
k /= 10;
20+
k += carry;
21+
i += 1;
22+
}
23+
24+
num.into_iter().rev().collect()
25+
}
26+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
function addToArrayForm(num: number[], k: number): number[] {
2+
num.reverse();
3+
let i = 0;
4+
5+
while (k > 0) {
6+
const digit = k % 10;
7+
i < num.length ? (num[i] += digit) : num.push(digit);
8+
9+
const carry = Math.floor(num[i] / 10);
10+
num[i] %= 10;
11+
12+
k = Math.floor(k / 10);
13+
k += carry;
14+
i++;
15+
}
16+
17+
return num.reverse();
18+
}

0 commit comments

Comments
 (0)