We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
public static int sum(String n) {
int j = n.length();
if(j == 1) {
return n.charAt(0)-'0';
}
if(j <= 0) {
return 0;
}
return (n.charAt(j-1)-'0')+ sum(n.substring(0,j-1));
}
public static int superDigit(String n, int k) {
int sum = 0;
int total = 0;
// Write your code here
if ((k == 1) && n.length() == 1) {
return (int) Integer.valueOf(n);
}
else {
for(int i = 0; i< n.length(); i++ ) {
sum = (n.charAt(i)-'0') * k;
int j = sum(String.valueOf(sum));
if(j < 10) {
total += j;
} else {
total += superDigit(String.valueOf(sum),1);
}
}
}
return total < 10 ? total:superDigit(String.valueOf(total),1) ;
}
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Recursive Digit Sum
You are viewing a single comment's thread. Return to all comments →
public static int sum(String n) { int j = n.length(); if(j == 1) { return n.charAt(0)-'0'; } if(j <= 0) { return 0; } return (n.charAt(j-1)-'0')+ sum(n.substring(0,j-1)); }
}