81. Round floating point number to integer
Declare integer y and initialize it with the rounded value of floating point number x . Ties (when the fractional part of x is exactly .5) must be rounded up (to positive infinity).
按规则取整
package main import ( "fmt" "math" ) func round(x float64) int { y := int(math.Floor(x + 0.5)) return y } func main() { for _, x := range []float64{-1.1, -0.9, -0.5, -0.1, 0., 0.1, 0.5, 0.9, 1.1} { fmt.Printf("%5.1f %5d\n", x, round(x)) } }
-1.1 -1 -0.9 -1 -0.5 0 -0.1 0 0.0 0 0.1 0 0.5 1 0.9 1 1.1 1
fn main() { let x : f64 = 2.71828; let y = x.round() as i64; println!("{} {}", x, y); }
82. Count substring occurrences
统计子字符串出现次数
package main import ( "fmt" "strings" ) func main() { s := "Romaromamam" t := "mam" x := strings.Count(s, t) fmt.Println(x) }
fn main() { let s = "lorem ipsum lorem ipsum lorem ipsum lorem ipsum"; let t = "ipsum"; let c = s.matches(t).count(); println!("{} occurrences", c); }
Disjoint matches: overlapping occurrences are not counted.
83. Regex with character repetition
Declare regular expression r matching strings "http", "htttp", "httttp", etc.
正则表达式匹配重复字符
package main import ( "fmt" "regexp" ) func main() { r := regexp.MustCompile("htt+p") for _, s := range []string{ "hp", "htp", "http", "htttp", "httttp", "htttttp", "htttttp", "word htttp in a sentence", } { fmt.Println(s, "=>", r.MatchString(s)) } }
hp => false htp => false http => true htttp => true httttp => true htttttp => true htttttp => true word htttp in a sentence => true
extern crate regex; use regex::Regex; fn main() { let r = Regex::new(r"htt+p").unwrap(); assert!(r.is_match("http")); assert!(r.is_match("htttp")); assert!(r.is_match("httttp")); }
84. Count bits set in integer binary representation
Count number c of 1s in the integer i in base 2.
E.g. i=6 → c=2
计算十进制整型的二进制表示中 1的个数
package main import "fmt" func PopCountUInt64(i uint64) (c int) { // bit population count, see // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel i -= (i >> 1) & 0x5555555555555555 i = (i>>2)&0x3333333333333333 + i&0x3333333333333333 i += i >> 4 i &= 0x0f0f0f0f0f0f0f0f i *= 0x0101010101010101 return int(i >> 56) } func PopCountUInt32(i uint32) (n int) { // bit population count, see // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel i -= (i >> 1) & 0x55555555 i = (i>>2)&0x33333333 + i&0x33333333 i += i >> 4 i &= 0x0f0f0f0f i *= 0x01010101 return int(i >> 24) } func main() { for i := uint64(0); i < 16; i++ { c := PopCountUInt64(i) fmt.Printf("%4d %04[1]b %d\n", i, c) } for i := uint32(0); i < 16; i++ { c := PopCountUInt32(i) fmt.Printf("%4d %04[1]b %d\n", i, c) } }
0 0000 0 1 0001 1 2 0010 1 3 0011 2 4 0100 1 5 0101 2 6 0110 2 7 0111 3 8 1000 1 9 1001 2 10 1010 2 11 1011 3 12 1100 2 13 1101 3 14 1110 3 15 1111 4 0 0000 0 1 0001 1 2 0010 1 3 0011 2 4 0100 1 5 0101 2 6 0110 2 7 0111 3 8 1000 1 9 1001 2 10 1010 2 11 1011 3 12 1100 2 13 1101 3 14 1110 3 15 1111 4
This was useful only before go 1.9. See math/bits.OnesCount instead
or
package main import ( "fmt" "math/bits" ) func main() { for i := uint(0); i < 16; i++ { c := bits.OnesCount(i) fmt.Printf("%4d %04[1]b %d\n", i, c) } }
0 0000 0 1 0001 1 2 0010 1 3 0011 2 4 0100 1 5 0101 2 6 0110 2 7 0111 3 8 1000 1 9 1001 2 10 1010 2 11 1011 3 12 1100 2 13 1101 3 14 1110 3 15 1111 4
fn main() { println!("{}", 6usize.count_ones()) }
85. Check if integer addition will overflow
检查两个整型相加是否溢出
package main import ( "fmt" "math" ) func willAddOverflow(a, b int64) bool { return a > math.MaxInt64-b } func main() { fmt.Println(willAddOverflow(11111111111111111, 2)) }
fn adding_will_overflow(x: usize, y: usize) -> bool { x.checked_add(y).is_none() } fn main() { { let (x, y) = (2345678, 9012345); let overflow = adding_will_overflow(x, y); println!( "{} + {} {}", x, y, if overflow { "overflows" } else { "doesn't overflow" } ); } { let (x, y) = (2345678901, 9012345678); let overflow = adding_will_overflow(x, y); println!( "{} + {} {}", x, y, if overflow { "overflows" } else { "doesn't overflow" } ); } { let (x, y) = (2345678901234, 9012345678901); let overflow = adding_will_overflow(x, y); println!( "{} + {} {}", x, y, if overflow { "overflows" } else { "doesn't overflow" } ); } { let (x, y) = (23456789012345678, 90123456789012345); let overflow = adding_will_overflow(x, y); println!( "{} + {} {}", x, y, if overflow { "overflows" } else { "doesn't overflow" } ); } { let (x, y) = (12345678901234567890, 9012345678901234567); let overflow = adding_will_overflow(x, y); println!( "{} + {} {}", x, y, if overflow { "overflows" } else { "doesn't overflow" } ); } }
2345678 + 9012345 doesn't overflow 2345678901 + 9012345678 doesn't overflow 2345678901234 + 9012345678901 doesn't overflow 23456789012345678 + 90123456789012345 doesn't overflow 12345678901234567890 + 9012345678901234567 overflows
86. Check if integer multiplication will overflow
检查整型相乘是否溢出
package main import ( "fmt" ) func multiplyWillOverflow(x, y uint64) bool { if x <= 1 || y <= 1 { return false } d := x * y return d/y != x } func main() { { var x, y uint64 = 2345, 6789 if multiplyWillOverflow(x, y) { fmt.Println(x, "*", y, "overflows") } else { fmt.Println(x, "*", y, "doesn't overflow") } } { var x, y uint64 = 2345678, 9012345 if multiplyWillOverflow(x, y) { fmt.Println(x, "*", y, "overflows") } else { fmt.Println(x, "*", y, "doesn't overflow") } } { var x, y uint64 = 2345678901, 9012345678 if multiplyWillOverflow(x, y) { fmt.Println(x, "*", y, "overflows") } else { fmt.Println(x, "*", y, "doesn't overflow") } } }
2345 * 6789 doesn't overflow 2345678 * 9012345 doesn't overflow 2345678901 * 9012345678 overflows
fn main() { { let (x, y) = (2345, 6789); let overflow = multiply_will_overflow(x, y); println!( "{} * {} {}", x, y, if overflow { "overflows" } else { "doesn't overflow" } ); } { let (x, y) = (2345678, 9012345); let overflow = multiply_will_overflow(x, y); println!( "{} * {} {}", x, y, if overflow { "overflows" } else { "doesn't overflow" } ); } { let (x, y) = (2345678901, 9012345678); let overflow = multiply_will_overflow(x, y); println!( "{} * {} {}", x, y, if overflow { "overflows" } else { "doesn't overflow" } ); } } fn multiply_will_overflow(x: i64, y: i64) -> bool { x.checked_mul(y).is_none() }
2345 * 6789 doesn't overflow 2345678 * 9012345 doesn't overflow 2345678901 * 9012345678 overflows
87. Stop program
Exit immediatly.
If some extra cleanup work is executed by the program runtime (not by the OS itself), describe it.
停止程序,立即退出。
package main import "os" func main() { os.Exit(1) print(2222) }
fn main() { std::process::exit(1); println!("42"); }
88. Allocate 1M bytes
分配1M内存
package main import "fmt" func main() { buf := make([]byte, 1000000) for i, b := range buf { if b != 0 { fmt.Println("Found unexpected value", b, "at position", i) } } fmt.Println("Buffer was correctly initialized with zero values.") }
fn main() { let buf: Vec<u8> = Vec::with_capacity(1024 * 1024); println!("{:?}", buf.capacity()); }
89. Handle invalid argument
处理无效参数
package main import "fmt" // NewSquareMatrix creates a N-by-N matrix func NewSquareMatrix(N int) ([][]float64, error) { if N < 0 { return nil, fmt.Errorf("Invalid size %d: order cannot be negative", N) } matrix := make([][]float64, N) for i := range matrix { matrix[i] = make([]float64, N) } return matrix, nil } func main() { N1 := 3 matrix1, err1 := NewSquareMatrix(N1) if err1 == nil { fmt.Println(matrix1) } else { fmt.Println(err1) } N2 := -2 matrix2, err2 := NewSquareMatrix(N2) if err2 == nil { fmt.Println(matrix2) } else { fmt.Println(err2) } }
[[0 0 0] [0 0 0] [0 0 0]] Invalid size -2: order cannot be negative
#[derive(Debug, PartialEq, Eq)] enum CustomError { InvalidAnswer } fn do_stuff(x: i32) -> Result<i32, CustomError> { if x != 42 { %2
90. Read-only outside
外部只读
type Foo struct { x int } func (f *Foo) X() int { return f.x }
x is private, because it is not capitalized. (*Foo).X is a public getter (a read accessor).
struct Foo { x: usize } impl Foo { pub fn new(x: usize) -> Self { Foo { x } } pub fn x<'a>(&'a self) -> &'a usize { &self.x } }