Last active
January 17, 2020 20:33
-
-
Save jakab922/dbcc165fd340fe981f69929f8dcc0d50 to your computer and use it in GitHub Desktop.
Rust solution to https://leetcode.com/problems/multiply-strings/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::vec::Vec; | |
impl Solution { | |
pub fn multiply(num1: String, num2: String) -> String { | |
let one: Vec<u32> = num1.chars().map(|c| c.to_digit(10).unwrap()).rev().collect(); | |
let other: Vec<u32> = num2.chars().map(|c| c.to_digit(10).unwrap()).rev().collect(); | |
let mut tmp: Vec<u32> = vec![0; one.len() + other.len() + 1]; | |
for (i, el1) in one.iter().enumerate() { | |
for (j, el2) in other.iter().enumerate() { | |
tmp[i + j] += el1 * el2; | |
} | |
} | |
let mut carry = 0; | |
let l = tmp.len(); | |
for i in 0..(l - 1) { | |
let curr = tmp[i] + carry; | |
tmp[i] = curr % 10; | |
carry = curr / 10; | |
} | |
tmp[l - 1] = carry; | |
let ret = tmp.into_iter().rev().skip_while(|&x| x == 0).map(|c| c.to_string()).collect::<String>(); | |
if ret.is_empty() { | |
return "0".to_string(); | |
} | |
ret | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment