Sort by

recency

|

45 Discussions

|

  • + 0 comments

    I tried doing this with common-lisp and realised there no string spliting function in standard lib lol.

    ;; SOLUTION
    (defun super-digit (int-str)
      "Parse each char of INT-STR as int then sum and stringify, repeat until single char."
      (if (= (length int-str) 1)
          (parse-integer int-str)
          ;; tail
          (super-digit
           ;; int-str
           (prin1-to-string
            (apply '+
                   (mapcar
                    (lambda (x) (- (char-int x) 48)) ; 48 is char code of 0
                    (coerce int-str 'list)))))))
    
    ;; this helps parsing stdin
    (defun split-string (str delim)
      (let ((acc '())
            (beg 0))
        (loop while (let ((end (position delim str :start beg)))
                      (progn
                        (push (subseq str beg end) acc)
                        (if end
                            (setq beg (+ 1 end))
                            nil ; break while
                            ))))
        (nreverse acc)))
    
    ;; MAIN
    (let* ((pair-n-k (split-string (read-line) #\Space))
           (n (car pair-n-k))
           (k (parse-integer (cadr pair-n-k))))
      (write (super-digit (prin1-to-string (* k (super-digit n))))))
    
  • + 0 comments
    def superDigit(n, k):
       # calculate inital n by adding n digits and multiplying it by k
        n = functools.reduce(operator.add,[int(i) for i in str(n)])*k    
        if len(str(n))==1:
           return n 
        return superDigit(int(n),1)
    
  • + 1 comment

    JS

    function superDigit(n, k) {
        let sum = n.split('').reduce((a, s) => a + Number(s), 0);
        let next = (sum * k) + "";
        return (next.length == 1) 
            ? Number(next) : superDigit(next, 1);
    }
    
  • + 0 comments

    java solution

    public static int super_Digit(String str, int k) { int num = Integer.parseInt(str);

        if (str.length() == 1) {
            return num;
        }
        int sum = 0;
    
        int rev = 0;
        while (num != 0) {
            rev = num % 10;
            sum = sum + rev;
            num = num / 10;
    
        }
    
        String newstring = String.valueOf(sum);
    
        return super_Digit(newstring, newstring.length());
    
    }
    
  • + 0 comments

    Python 3 solution... Needed a bit of an optimization to avoid memory issue (e.g. the initial_super_digit calculation).

    def _super_digit(n):
        if len(str(n)) == 1:
            return n
        return _super_digit(sum([int(c) for c in str(n)]))
    
    def superDigit(n, k):
        initial_super_digit = _super_digit(n)
        return _super_digit(initial_super_digit * k)