oppgaver så langt
This commit is contained in:
parent
4f3385850f
commit
df84d4f18e
17 changed files with 628 additions and 0 deletions
66
add-binary-67/src/main.rs
Normal file
66
add-binary-67/src/main.rs
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
struct Solution {}
|
||||
|
||||
impl Solution {
|
||||
pub fn add_binary(a: String, b: String) -> String {
|
||||
let mut result = String::new();
|
||||
let mut carry = 0;
|
||||
|
||||
// Convert strings to character vectors and reverse them for easier processing
|
||||
let a_chars: Vec<char> = a.chars().rev().collect();
|
||||
let b_chars: Vec<char> = b.chars().rev().collect();
|
||||
|
||||
// Get the maximum length of the two strings
|
||||
let max_len = std::cmp::max(a_chars.len(), b_chars.len());
|
||||
|
||||
// Perform binary addition digit by digit
|
||||
for i in 0..max_len {
|
||||
// Get digits at current position or 0 if we've reached the end
|
||||
let a_digit = if i < a_chars.len() {
|
||||
a_chars[i].to_digit(2).unwrap()
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let b_digit = if i < b_chars.len() {
|
||||
b_chars[i].to_digit(2).unwrap()
|
||||
} else {
|
||||
0
|
||||
};
|
||||
|
||||
// Calculate sum and new carry
|
||||
let sum = a_digit + b_digit + carry;
|
||||
carry = sum / 2;
|
||||
let digit = sum % 2;
|
||||
|
||||
// Add the current digit to the result
|
||||
result.push(char::from_digit(digit, 2).unwrap());
|
||||
}
|
||||
|
||||
// Don't forget the final carry if it exists
|
||||
if carry > 0 {
|
||||
result.push('1');
|
||||
}
|
||||
|
||||
// Reverse the result and return
|
||||
result.chars().rev().collect()
|
||||
}
|
||||
|
||||
// pub fn add_binary(a: String, b: String) -> String {
|
||||
// let num1 = u128::from_str_radix(a.as_str(), 2).expect("Valid binary string");
|
||||
// let num2 = u128::from_str_radix(b.as_str(), 2).expect("Valid binary string");
|
||||
|
||||
// let sum = num1 + num2;
|
||||
|
||||
// let binary_sum = format!("{:b}", sum); // format as binary string
|
||||
|
||||
// println!("Sum in decimal: {}", sum);
|
||||
// println!("Sum in binary: {}", binary_sum);
|
||||
// binary_sum
|
||||
// }
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let a: String = "111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111".to_string();
|
||||
let b: String = "11010100101110111000111".to_string();
|
||||
|
||||
println!("{:?}", Solution::add_binary(a, b));
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue