You are viewing a single comment's thread. Return to all 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); } }
It's not really working for all of the test cases.
use
num = (num + n%10 )%9;
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))); }
awesome code man. my function is exactly same as urs but I am unable to break the string.
why it didn't throw runtime error?? this solution includes many loops :\
@Singhalr31 Well, based on the comments from @swapnilsingh1023 : "It's not really working for all of the test cases." :(
Seems like cookies are disabled on this browser, please enable them to open this website
I agree to HackerRank's Terms of Service and Privacy Policy.
Recursive Digit Sum
You are viewing a single comment's thread. Return to all comments →
Here is recursive solution
It's not really working for all of the test cases.
use
num = (num + n%10 )%9;
This code is working
awesome code man. my function is exactly same as urs but I am unable to break the string.
why it didn't throw runtime error?? this solution includes many loops :\
@Singhalr31 Well, based on the comments from @swapnilsingh1023 : "It's not really working for all of the test cases." :(