1、动态数组vec遍历
1)带索引遍历
impl Solution {
pub fn running_sum(nums: Vec<i32>) -> Vec<i32> {
let mut numstmp = Vec::new();
numstmp.push(nums[0]);
for (idx, val) in nums.iter().enumerate(){
if idx ==0 {continue;}
let numtmp = &nums[idx]+&numstmp[idx-1];
numstmp.push(numtmp)
}
numstmp
}
}
2)带索引遍历+求和
impl Solution {
pub fn maximum_wealth(accounts: Vec<Vec<i32>>) -> i32 {
let mut max_val = 0;
for (i,i_val) in accounts.iter().enumerate(){
let sum = accounts[i].iter().sum();
if sum > max_val{
max_val = sum;
}
}
max_val
}
}
2 while循环
impl Solution {
pub fn number_of_steps(num: i32) -> i32 {
if num==0 { return 0; }
let mut step =1;
let mut numtmp = num;
while numtmp >1 {
step+=1;
if numtmp & 1 == 1 {numtmp-=1;}else{numtmp /=2;}
}
return step;
}
}
3 整型和字符串互转
let int_value = 5;
//整型转字符串
let string_value = int_value.to_string();
//字符串转32位有符号整型
let back_int = string_value.parse::<i32>().unwrap();
// 字符串转32位无符号整型
let back_int = string_value.parse::<u32>().unwrap();
//字符串转16位有符号整型
let back_int = string_value.parse::<i16>().unwrap();
————————————————
版权声明:本文为CSDN博主「weixin_44222183」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_44222183/article/details/119572452
4 match 学习
impl Solution {
pub fn fizz_buzz(n: i32) -> Vec<String> {
(1..n+1).map(|i|
match (0==i%3,0==i%5) {
(true,true)=>"FizzBuzz".to_string(),
(true,false)=>"Fizz".to_string(),
(false,true)=>"Buzz".to_string(),
_=>i.to_string()
}
).collect()
}
}
作者:java_Lee
链接:https://leetcode.cn/problems/fizz-buzz/solution/rust-die-dai-qi-xie-fa-by-java_lee-4kry/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
impl Solution {
pub fn fizz_buzz(n: i32) -> Vec<String> {
let mut result = Vec::new();
for i in 1..=n {
let r = match i {
_ if i%3==0 && i%5==0 => String::from("FizzBuzz"),
_ if i % 3 ==0 => String::from("Fizz"),
_ if i % 5 ==0 => String::from("Buzz"),
_ => i.to_string()
};
result.push(r);
}
result
}
}
作者:java_Lee
链接:https://leetcode.cn/problems/fizz-buzz/solution/rust-die-dai-qi-xie-fa-by-java_lee-4kry/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
#[derive(Debug)]
enum List {
Node(i32, Box<List>), // 使用Box标记类型
Nil,
}
let list = List::Node(1,
Box::new(List::Node(2,
Box::new(List::Node(3,
Box::new(List::Nil))
)
))
);
println!("{:?}", list);
// Node(1, Node(2, Node(3, Nil)))
pub fn average_value(nums: Vec<i32>) -> i32 { let (sum, cnt) = nums.iter().filter(|x| *x % 6 == 0).fold((0, 0), |(sum, cnt), &x| (sum + x, cnt + 1) ); if cnt == 0 { 0 } else { sum / cnt } }