Skip to content

Instantly share code, notes, and snippets.

@v2keener
Last active August 29, 2015 14:06
Show Gist options
  • Save v2keener/de07bbf6d0c206af4b88 to your computer and use it in GitHub Desktop.
Save v2keener/de07bbf6d0c206af4b88 to your computer and use it in GitHub Desktop.
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