搜尋此網誌
2025年11月30日 星期日
Rust: triangles from smallest/largest to largest/smallest
fn main() {
println!("triangles from smallest to largest");
let mut count0 = 0;
let mut count1 = 1;
loop {
loop {
if count0 >= count1 {
break; // exit loop
}
print!("*");
count0 += 1;
}
if count1 >= 5 {
break; // exit loop
}
println!("");
count1 += 1;
count0 = 0;
}
}
triangles from smallest to largest
*
**
***
****
*****
fn main() {
println!("triangles from largest to smallest");
let mut count0 = 5;
let mut count1 = 5;
loop {
loop {
if count0 <= 0 {
break; // exitloop
}
print!("*");
count0 -= 1;
}
if count1 <= 0 {
break; // exit loop
}
println!("");
count1 -= 1;
count0 = count1;
}
}
triangles from largest to smallest
*****
****
***
**
*
2025年11月9日 星期日
找右邊算來第一個1的bit位置
#include <stdio.h>
int calculate_first_one_in_left(unsigned int n)
{
int start = 0, shift_r_num = 0;
while(1)
{
if (n == 0) {
shift_r_num = (start == 0) ? -1 : (shift_r_num - 1) ;
break;
}
start = 1;
n >>= 1;
shift_r_num ++;
}
return shift_r_num;
}
int main()
{
unsigned int n=0x1100;
printf ("n=0x%x, %d\n", n, calculate_first_one_in_left(n));
n=0x100;
printf ("n=0x%x, %d\n", n, calculate_first_one_in_left(n));
n=0x10;
printf ("n=0x%x, %d\n", n, calculate_first_one_in_left(n));
n=0x1;
printf ("n=0x%x, %d\n", n, calculate_first_one_in_left(n));
return 0;
}
[Output]
n=0x1100, 12
n=0x100, 8
n=0x10, 4
n=0x1, 0
訂閱:
意見 (Atom)