Recursive Digit Sum

  • + 3 comments

    Here is recursive solution

    static int superDigit(String n, int k) {
          long num = 0; 
          for(int i=0; i<n.length(); i++) {
              num += Integer.parseInt(n.charAt(i)+"");
          } 
          num =  helper(num*k);
          int num2 = (int) num;
          return num2;
        }
        private static long helper(long n) {
          if(n<10) {
            return n; 
          }
          else {
            int num = 0;
            while(n>0) {
              num += n % 10;
              n = n/10; 
            } 
            return helper(num); 
          }
         
         }     
    
    • + 2 comments

      It's not really working for all of the test cases.

      • + 0 comments

        use

        num = (num + n%10 )%9;

      • + 0 comments

        This code is working

        static long getNum(String n){
                long num = 0;
                for(char c : n.toCharArray())
                    num += Character.digit(c, 10);
                return num;
            }
            static int superDigit(String n){
                System.out.println(n);
                if(n.length() <= 1) return Integer.parseInt(n);
                return superDigit(String.valueOf(getNum(n))); 
            }
            static int superDigit(String n, int k) {
                return superDigit(String.valueOf(k * getNum(n)));
            }
        
    • + 0 comments

      awesome code man. my function is exactly same as urs but I am unable to break the string.

    • + 1 comment

      why it didn't throw runtime error?? this solution includes many loops :\

      • + 0 comments

        @Singhalr31 Well, based on the comments from @swapnilsingh1023 : "It's not really working for all of the test cases." :(