Task

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

   110         sums to   1
   123410   sums to   10
   fe16       sums to   29
   f0e16     sums to   29


/* NetRexx */
options replace format comments java crossref symbols nobinary
 
parse arg input
inputs = ['1234', '01234', '0xfe', '0xf0e', '0', '00', '0,2' '1', '070', '77, 8' '0xf0e, 10', '070, 16', '0xf0e, 36', '000999ABCXYZ, 36', 'ff, 16', 'f, 10', 'z, 37'] -- test data
if input.length() > 0 then inputs = [input] -- replace test data with user input
loop i_ = 0 to inputs.length - 1
  in = inputs[i_]
  parse in val . ',' base .
  dSum = sumDigits(val, base)
  say 'Sum of digits for integer "'val'" for a given base of "'base'":' dSum'\-'
  -- Carry the exercise to it's logical conclusion and sum the results to give a single digit in range 0-9
  loop while dSum.length() > 1 & dSum.datatype('n')
    dSum = sumDigits(dSum, 10)
    say ',' dSum'\-'
    end
  say
  end i_
 
-- Sum digits of an integer
method sumDigits(val = Rexx, base = Rexx '') public static returns Rexx
 
  rVal = 0
  parse normalizeValue(val, base) val base .
  loop label digs for val.length()
    -- loop to extract digits from input and sum them
    parse val dv +1 val
    do
      rVal = rVal + Integer.valueOf(dv.toString(), base).intValue()
    catch ex = NumberFormatException
      rVal = 'NumberFormatException:' ex.getMessage()
      leave digs
    end
    end digs
  return rVal
 
-- Clean up the input, normalize the data and determine which base to use
method normalizeValue(inV = Rexx, base = Rexx '') private static returns Rexx
  inV = inV.strip('l')
  base = base.strip()
  parse inV xpref +2 . -
         =0 opref +1 . -
         =0 . '0x' xval . ',' . -
         =0 . '0'  oval . ',' . -
         =0 dval .
 
  select
    when xpref = '0x' & base.length() = 0 then do
      -- value starts with '0x' and no base supplied.  Assign hex as base
      inval = xval
      base = 16
      end
    when opref = '0'  & base.length() = 0 then do
      -- value starts with '0' and no base supplied.  Assign octal as base
      inval = oval
      base = 8
      end
    otherwise do
      inval = dval
      end
    end
  if base.length() = 0 then base = 10 -- base not set.  Assign decimal as base
  if inval.length() <= 0 then inval = 0 -- boundary condition.  Invalid input or a single zero
  rVal = inval base
 
  return rVal
 