Advertisement
sword_smith

Can this be written without an if?

Jan 5th, 2023
1,702
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 0.55 KB | None | 0 0
  1. pub fn non_leaf_nodes_left(data_index: u128) -> u128 {
  2.     // This formula is derived as follows:
  3.     // To get the heights of peaks before this data index was inserted, bit-decompose
  4.     // the number of leaves before it was inserted.
  5.     // Number of leaves in tree of height h = 2^h
  6.     // Number of nodes in tree of height h = 2^(h + 1) - 1
  7.     // Number of non-leaves is `#(nodes) - #(leaves)`.
  8.     let mut ret = 0;
  9.     for h in 0..u128::BITS {
  10.         if (1 << h) & data_index != 0 {
  11.             ret += (1 << h) - 1;
  12.         }
  13.     }
  14.  
  15.     ret
  16. }
Advertisement
Comments
Add Comment
Please, Sign In to add comment
Advertisement