We define the super digit of an integer x using the following rules:
Given an integer, we need to find the super digit of the integer.
- If x has only 1 digit, then its super digit is x.
- Otherwise, the super digit of x is equal to the super digit of the sum of the digits of x.
Example:
Input: s="9875" , k=4
Output: 8
Approach
Java
public class RecursiveDigitSum {public static void main(String[] args) {String n = "9875";int k = 4;int sum = superDigit(n, k);System.out.println(sum);}static int superDigit(String s, int k) {double sum = 0;for (int i = 0; i < s.length(); i++) {sum += s.charAt(i) - '0';}sum = sum * k;while (sum >= 10) {sum = digitSum(sum);}int n = (int) sum;return n;}// function to find the sum of// digits of a numberstatic int digitSum(double n) {int sum = 0;while (n > 0) {sum += n % 10;n = n / 10;}return sum;}}
C++
#include <bits/stdc++.h>using namespace std;//function to find the sum of//digits of a numberlong long int digitSum(long long int n){long long int sum = 0;while (n > 0){sum += n % 10;n = n / 10;}return sum;}int main(){string s = "9875";long long int k = 4;long long int sum = 0;for (long long int i = 0; i < s.size(); i++){sum += s[i] - '0';}sum = sum * k;while (sum >= 10){sum = digitSum(sum);}cout << sum << "\n";return 0;}
No comments:
Post a Comment