2020-07-16

Binary Concatenation

嘗試用 Tcl 解題:
#!/usr/bin/env tclsh
#
# The concatenation of the first four integers, written in binary, is 11011100; 
# that is, 1 followed by 10 followed by 11 followed by 100. That concatenated 
# number resolves to 220. A similar process can convert the concatenation of 
# the first n binary numbers to a normal decimal number.
#

proc bitcat {number} {
    # Convert decimal to binary and collect the result
    set result ""
    for {set i 1} {$i <= $number} {incr i} {
        append result [format %llb $i]
    }

    return $result
}

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

puts [expr (0b[bitcat $number]) % ((10 ** 9) + 7)]

也可以這樣解:
#!/usr/bin/env tclsh
#
# The concatenation of the first four integers, written in binary, is 11011100; 
# that is, 1 followed by 10 followed by 11 followed by 100. That concatenated 
# number resolves to 220. A similar process can convert the concatenation of 
# the first n binary numbers to a normal decimal number.
#
proc bitcat {result index} {
    for {set counter $index} {$counter > 0} {set counter [::tcl::mathop::>> $counter 1]} {
         set result [::tcl::mathop::<< $result 1]
    }

    return [::tcl::mathop::| $result $index]
}

proc solution {number} {
    set result 0
    for {set index 1} {$index <= $number} {incr index} {
        set result [bitcat $result $index]
    }

    return [expr $result % ((10 ** 9) + 7)]
}

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

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

2020-07-04

tcljsonnet v0.13

首頁:
tcljsonnet


主要更新:
將 Jsonnet code base 版本升到 v0.16.0 版。