How to resolve the algorithm Sum digits of an integer step by step in the Tcl programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Sum digits of an integer step by step in the Tcl programming language

Table of Contents

Problem Statement

Take a   Natural Number   in a given base and return the sum of its digits:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Sum digits of an integer step by step in the Tcl programming language

Source code in the tcl programming language

proc sumDigits {num {base 10}} {
    set total 0
    foreach d [split $num ""] {
	if {[string is alpha $d]} {
	    set d [expr {[scan [string tolower $d] %c] - 87}]
	} elseif {![string is digit $d]} {
	    error "bad digit: $d"
	}
	if {$d >= $base} {
	    error "bad digit: $d"
	}
	incr total $d
    }
    return $total
}

puts [sumDigits 1]
puts [sumDigits 12345]
puts [sumDigits 123045]
puts [sumDigits fe 16]
puts [sumDigits f0e 16]
puts [sumDigits 000999ABCXYZ 36]

  

You may also check:How to resolve the algorithm Priority queue step by step in the PicoLisp programming language
You may also check:How to resolve the algorithm Bitmap/PPM conversion through a pipe step by step in the zkl programming language
You may also check:How to resolve the algorithm JortSort step by step in the jq programming language
You may also check:How to resolve the algorithm Wordle comparison step by step in the V (Vlang) programming language
You may also check:How to resolve the algorithm Extend your language step by step in the Ruby programming language