2020-07-10

Trailing Zero-Bits

下面是我嘗試的答案:
#!/usr/bin/env tclsh
#
# Trailing Zero-Bits
# Given a positive integer, count the number of trailing zero-bits in its binary 
# representation. For instance, 18 = 10010, so it has 1 trailing zero-bit, 
# and 48 = 110000, so it has 4 trailing zero-bits.
#

puts -nonewline "Please input a number: "
flush stdout
gets stdin number
if {$number <= 0} {
    puts "Number requires > 0."
    exit
}

set trailing {{number} {
    set index 0
    while {[::tcl::mathop::& $number 1]!=1} {
        incr index
        set number [::tcl::mathop::>> $number 1]
    }
    return $index
}}

set count [apply $trailing $number]
puts $count

沒有留言: