How to resolve the algorithm Sum digits of an integer step by step in the Scala 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 Scala 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 Scala programming language
Source code in the scala programming language
def sumDigits(x:BigInt, base:Int=10):BigInt=sumDigits(x.toString(base), base)
def sumDigits(x:String, base:Int):BigInt = x map(_.asDigit) sum
sumDigits(0) // => 0
sumDigits(0, 2) // => 0
sumDigits(0, 16) // => 0
sumDigits("00", 2) // => 0
sumDigits("00", 10) // => 0
sumDigits("00", 16) // => 0
sumDigits(1234) // => 10
sumDigits(0xfe) // => 11
sumDigits(0xfe, 16) // => 29
sumDigits(0xf0e, 16) // => 29
sumDigits(077) // => 9
sumDigits(077, 8) // => 14
sumDigits("077", 8) // => 14
sumDigits("077", 10) // => 14
sumDigits("077", 16) // => 14
sumDigits("0xf0e", 36) // => 62
sumDigits("000999ABCXYZ", 36) // => 162
sumDigits(BigInt("12345678901234567890")) // => 90
sumDigits("12345678901234567890", 10) // => 90
You may also check:How to resolve the algorithm Sailors, coconuts and a monkey problem step by step in the Clojure programming language
You may also check:How to resolve the algorithm Matrix transposition step by step in the Factor programming language
You may also check:How to resolve the algorithm Read a file character by character/UTF8 step by step in the Seed7 programming language
You may also check:How to resolve the algorithm N'th step by step in the Prolog programming language
You may also check:How to resolve the algorithm Pythagorean triples step by step in the CoffeeScript programming language