From dddf4ac7dd9839c30d494c98911ed4bb7ad02ff4 Mon Sep 17 00:00:00 2001 From: li-chx Date: Fri, 5 Sep 2025 11:41:56 +0800 Subject: [PATCH] =?UTF-8?q?2749.=20=E5=BE=97=E5=88=B0=E6=95=B4=E6=95=B0?= =?UTF-8?q?=E9=9B=B6=E9=9C=80=E8=A6=81=E6=89=A7=E8=A1=8C=E7=9A=84=E6=9C=80?= =?UTF-8?q?=E5=B0=91=E6=93=8D=E4=BD=9C=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main.rs | 108 +++++++++++++++++++++++++++------------------------- 1 file changed, 56 insertions(+), 52 deletions(-) diff --git a/src/main.rs b/src/main.rs index 08c0e4b..3824058 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,62 +1,66 @@ +use std::cmp::min; + struct Solution; impl Solution { - pub fn spiral_order(matrix: Vec>) -> Vec { - let mut top_x = 0; - let mut left_y = 0; - let mut bottom_x = matrix.len() as i32 - 1; - let mut right_y = matrix[0].len() as i32 - 1; - let mut next_x = 0; - let mut next_y = 1; - let mut pos = (0, 0); - - let mut res = vec![matrix[0][0]]; - - let mut next_pos = || { - let mut new_pos = (pos.0 + next_x, pos.1 + next_y); - if new_pos.0 > bottom_x || new_pos.0 < top_x || new_pos.1 > right_y || new_pos.1 < left_y { - (next_x, next_y) = match (next_x, next_y) { - (0, 1) => { - top_x += 1; - (1, 0) - } - (1, 0) => { - right_y -= 1; - (0, -1) - } - (0, -1) => { - bottom_x -= 1; - (-1, 0) - } - (-1, 0) => { - left_y += 1; - (0, 1) - } - _ => (0, 0), - }; - - new_pos = (pos.0 + next_x, pos.1 + next_y); - if new_pos.0 > bottom_x - || new_pos.0 < top_x - || new_pos.1 > right_y - || new_pos.1 < left_y - { - return false; + 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); + } + 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; } } - pos = new_pos; - res.push(matrix[pos.0 as usize][pos.1 as usize]); - true - }; - while next_pos() {} - res + 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; + } + } + -1 } } fn main() { - let sl = Solution::spiral_order(vec![ - vec![1, 2, 3, 4], - vec![5, 6, 7, 8], - vec![9, 10, 11, 12], - ]); + let sl = Solution::make_the_integer_zero(34,9); println!("{:?}", sl); }