Last active
August 29, 2015 14:06
-
-
Save v2keener/de07bbf6d0c206af4b88 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object SumDigits { | |
def main(args: Array[String]) { | |
println("heelo [sic] world"); | |
sumDigits(94); //13 | |
sumDigits(32); //5 | |
sumDigits(44); //8 | |
sumDigits(5232); //12 | |
sumDigits(3535235); //26 | |
sumDigits(2147483647); //46 (Int [31 bit + 1 bit for sign] max value) | |
} | |
def sumDigits(arg: Int) { | |
def absArg = scala.math.abs(arg); //As a precondition, I *could* say I only accept natural numbers. I could. | |
var power: Long = 1; // All Int values accepted, power must go to 100000000000 (exceeds max Int value) | |
var sizeArg = absArg % power; // 0 | |
// Accumulate our modulus operand [power] by measuring the results of increasing modulo ops | |
while (sizeArg != absArg) { | |
power = power * 10; | |
sizeArg = absArg % power; | |
} | |
var digitSum: Int = 0; | |
var argVar: Int = absArg; | |
// Accumulate sum of digits | |
while (power > 1) { | |
// Get single-digit value from integer at [tens] place | |
var digit = ((argVar - (argVar % power)) / power).toInt; | |
digitSum = digitSum + digit; | |
// Remove digit we just added to digitSum | |
argVar = (argVar % power).toInt; | |
// Go to next lower power of 10s | |
power = power / 10; | |
} | |
// Add the last digit | |
digitSum = digitSum + (arg % 10); | |
printf("Sum of %d is %d\n", arg, digitSum); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment