Roger
Roger

Reputation: 8576

Sum digits of a number while greater than 2 digits

The challenge is to sum the digits of a given number till the result has only one digit. Let say the number is "999" (9+9+9=27, 2+7=9). This is what I did till now.

#!/bin/bash
set +m
shopt -s lastpipe

NUMBER=999

DIGITS=`echo "${#NUMBER}"`
FINALSUM=0

if [ "$DIGITS" -gt 0 ] && [ "$DIGITS" -gt 1 ]; then
    grep -o . <<< "${NUMBER}" | while read DIGIT;  do
        declare -x FINALSUM="$(($FINALSUM+$DIGIT))"
    done
    echo $FINALSUM
else
    echo $SOMA
fi

Upvotes: 0

Views: 186

Answers (2)

Walter A
Walter A

Reputation: 20022

A bit slow for large numbers:

function sumit {
   i="$1"
   while  [ "$i" -gt 10 ]; do
      (( i=i%10 + i/10 ))
   done
   echo "$1 => $i"
}

# Test
for i in 10 15 999 222 2229; do
   sumit $i
done

Upvotes: 1

James Brown
James Brown

Reputation: 37414

Can an awk-ward guy join in?

$ awk -v i=999 '
BEGIN {
    while( split(i,a,"") > 1) { 
        i=0; 
        for( j in a ) i+=a[j]
    }
    print i
}'
9

Upvotes: 1

Related Questions