carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode989:数组形式的整数加法(add-to-array-form-of-integer) #175

Open carloscn opened 1 year ago

carloscn commented 1 year ago

问题描述

整数的 数组形式  num 是按照从左到右的顺序表示其数字的数组。

例如,对于 num = 1321 ,数组形式是 [1,3,2,1] 。 给定 num ,整数的 数组形式 ,和整数 k ,返回 整数 num + k 的 数组形式 。

 

示例 1:

输入:num = [1,2,0,0], k = 34 输出:[1,2,3,4] 解释:1200 + 34 = 1234 示例 2:

输入:num = [2,7,4], k = 181 输出:[4,5,5] 解释:274 + 181 = 455 示例 3:

输入:num = [2,1,5], k = 806 输出:[1,0,2,1] 解释:215 + 806 = 1021  

提示:

1 <= num.length <= 104 0 <= num[i] <= 9 num 不包含任何前导零,除了零本身 1 <= k <= 104

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/add-to-array-form-of-integer

carloscn commented 1 year ago

问题分析

准备一个遍历数组的i值,i从数组的尾部开始遍历。取数组的个位十位百位(pos),记录求和sum,记录进位prom,sum = pos + prom + array[i] % 10; 最后如果prom != 0 需要ret_vec.insert(0, prom)

pub fn add_to_array_form(num: Vec<i32>, k: i32) -> Vec<i32>
{
    if 0 == k {
        return num;
    }
    let mut k_t = k;
    let mut k_vec:Vec<i32> = vec![];
    while k_t != 0 {
        k_vec.insert(0,k_t % 10);
        k_t /= 10;
    }
    if num.len() == 0 {
        return k_vec;
    }
    let mut p_k:i32;
    let mut n_k:i32;
    let mut i:i32 = (k_vec.len() - 1) as i32;
    let mut j:i32 = (num.len() - 1) as i32;
    let mut prom:i32 = 0;
    let mut sum:i32;
    let mut ret_vec:Vec<i32> = vec![];
    while i != -1 || j != -1 {
        if i != -1 {
            p_k = k_vec[i as usize];
            i -= 1;
        } else {
            p_k = 0;
        }
        if j != -1 {
            n_k = num[j as usize];
            j -= 1;
        } else {
            n_k = 0;
        }
        sum = prom + p_k + n_k;
        ret_vec.insert(0, sum % 10);
        prom = sum / 10;
    }
    if prom != 0 {
        ret_vec.insert(0, prom);
    }
    return ret_vec;
}
carloscn commented 1 year ago

code

https://github.com/carloscn/structstudy/commit/0038b08d49a4ba572cd9b0b6cd18bec39e79324f https://review.gerrithub.io/c/carloscn/structstudy/+/552093