rust_test/src/main.rs

67 lines
1.7 KiB
Rust
Raw Normal View History

use std::cmp::min;
struct Solution;
impl Solution {
pub fn make_the_integer_zero(num1: i32, num2: i32) -> i32 {
fn max_able_contains_two(number: u64) -> i64{
let mut ans : i64= 0;
let mut index = 0;
for i in 0..64 {
if (number >> i) & 1 == 1 {
ans += 2_i64.pow(index);
2025-08-18 14:16:41 +08:00
}
index += 1;
}
ans
}
fn check(num1: i64, num2: i64, k: i64) -> bool {
let new_num1 = num1 - k * num2;
if new_num1 < 0 {
return false;
}
let max_cnt = max_able_contains_two(new_num1 as u64);
let min_cnt = new_num1.count_ones() as i64;
k >= min_cnt && k <= max_cnt
}
let mut l = 0;
let mut r = 1_000_000_010;
let num1 = num1 as i64;
let num2 = num2 as i64;
if num2 > 0 {
r = min(r, num1 / num2);
let mut have_ans = false;
for i in (0..r + 1).rev() {
if check(num1,num2,i) {
r = i;
have_ans = true;
break;
}
}
if !have_ans {
return -1;
}
}
while l < r {
let mid = (l + r) / 2;
if check(num1, num2, mid) {
r = mid;
}else {
l = mid + 1;
}
}
if l == 1_000_000_010 { return -1; }
for i in 1..l + 1 {
if check(num1, num2, i) {
return i as i32;
2025-08-18 14:16:41 +08:00
}
}
-1
}
}
fn main() {
let sl = Solution::make_the_integer_zero(34,9);
println!("{:?}", sl);
}