Recursive Digit Sum

Sort by

recency

|

58 Discussions

|

  • + 0 comments

    There is a faster method creating a new recursive function that only works with numbers instead of string, but not sure if that was asked, because of how the question was structured.

    Also, you can not even use recursion and just take (n*k)%9, but seems kinda magic

    Python best solution

    If you’re looking for solutions to the 3-month preparation kit in either Python or Rust, you can find them below: my solutions

    def superDigit(n, k):
        if (len(n) == 1) and (k == 1):
            return int(n)
    
        sum = 0
        for number in n:
            sum += int(number)
        return superDigit(str(sum * k), 1)
    
  • + 0 comments

    There is a faster method creating a new recursive function that only works with numbers instead of string, but not sure if that was asked, because of how the question was structured.

    Also, you can not even use recursion and just take (n*k)%9, but seems kinda magic

    Rust best solution

    If you’re looking for solutions to the 3-month preparation kit in either Python or Rust, you can find them below: my solutions

    fn superDigit(n: &str, k: i32) -> i32 {
        if (n.len() == 1) && (k == 1) {
            return n.parse::<i32>().unwrap();
        }
    
        let mut sum = 0;
        for number in n.chars() {
            let number = number.to_digit(10).unwrap();
            sum += number;
        }
        if k != 1 {
            sum = (superDigit(&(sum as i32).to_string(), 1) * k) as u32;
        }
        superDigit(&(sum as i32).to_string(), 1) * 1
    }
    
  • + 0 comments

    C#:

    public static int superDigit(string n, int k)
        {
            do
            {
                long sum = 0;
                foreach(char c in n)
                {
                    sum += int.Parse(c.ToString());
                }
                sum *= k;
                k=1;
                n = sum.ToString();
            }while(n.Count()!=1);
            
            return int.Parse(n);
        }
    
  • + 0 comments

    TypeScript

    function superDigit(n: string, k: number): number {
      let sum = 0;
    
      for (let char of n) {
        sum += Number(char);
      }
    
      sum *= k;
    
      if (sum <= 9) return sum;
    
      return superDigit(String(sum), 1);
    }
    
  • + 0 comments

    php

    function superDigit($n, $k) {
        $x = array_sum(str_split($n)) * $k;
    
        while ($x >= 10) {
            $x = array_sum(str_split($x));
        }
    
        return $x;
    }