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]

沒有留言: