Recursive Digit Sum – HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.
Solutions of Algorithms Data Structures Hard HackerRank:
Here are all the Solutions of Hard , Advanced , Expert Algorithms of Data Structure of Hacker Rank , Leave a comment for similar posts
1 Month Preparation Kit Solutions – HackerRank
C++ Recursive Digit Sum HackerRank Solution
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int super_digit( long long k ) {
if ( k < 10 ) {
return k;
}
long long sum = 0;
while( k > 0 ) {
sum += k % 10;
k = k / 10;
}
return super_digit( sum );
}
long long sum_initial( string number ){
long long sum = 0;
for( int i = 0; i < number.size(); i++ ) {
sum += number[i] - '0';
}
return sum;
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
string n;
int k;
cin >> n >> k;
long long repeated = sum_initial(n) * k;
long long result = super_digit(repeated);
cout << result << "\n";
return 0;
}
Java Recursive Digit Sum HackerRank Solution
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Solution s = new Solution();
Scanner sc = new Scanner(System.in);
String str_n = sc.next();
int k = sc.nextInt();
int pSum = Integer.parseInt(s.supdig(str_n));
pSum *= k;
String sup = Integer.toString(s.supdig(pSum));
System.out.println(sup);
}
String supdig(String n) {
if(n.length() == 1) return n;
else {
int np = 0;
for(int i = 0; i < n.length(); i++) {
np += Character.getNumericValue( n.charAt(i) );
}
return supdig(Integer.toString(np));
}
}
int supdig(int n) {
if(n / 10 == 0) return n;
else {
int r = 0;
while(n > 0) {
r += n % 10;
n /= 10;
}
return supdig(r);
}
}
}
Python 3 Recursive Digit Sum HackerRank Solution
def sup_digits(x,k):
a = digsum(x)
return sup_digit(str(int(a)*k))
def sup_digit(x):
if len(x) <= 1:
return x
else:
return sup_digit( digsum(x) )
def digsum(x):
return str(sum((int(i) for i in list(x))))
n, k = input().split()
print( sup_digits(n, int(k)))
JavaScript Recursive Digit Sum HackerRank Solution
const N = require('bignumber.js');
let $ = '';
const r = n => n < 10 ? n : f(new N(n).toFixed());
const f = (n, k = 1) => {
let i = 0;
for (const c of n) i += +c;
return r(i * k);
};
process.stdin.on('data', d => $ += d).on('end', () => {
const [ n, k ] = $.trim().split(/\s+/);
const ans = f(new N(n).toFixed(), +k);
console.log(ans);
});
C Recursive Digit Sum HackerRank Solution
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
long long sd=0,h;
int k;
int c;
do{
c=getchar();
if(c != ' ')
sd += c -'0';
}while(c != ' ');
scanf("%d",&k);
sd *= k;
while(sd > 10){
h=0;
while(sd > 0){
h+= sd %10;
sd = sd /10;
}
sd =h;
}
printf("%lld\n",sd);
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
return 0;
}
Leave a comment below