# Additive Persistence Coderbyte Solution

0

Have the function AdditivePersistence(num) take the num parameter being passed which will always be a positive integer and return its additive persistence which is the number of times you must add the digits in num until you reach a single digit.

For example: if num is 2718 then your program should return 2 because 2 + 7 + 1 + 8 = 18 and 1 + 8 = 9 and you stop at 9.

Additive Persistence Java

import java.util.Scanner;

public class AdditivePersistence {
int AdditivePersistence(int num) {
return getAddPersistence(num, 0);
}

int getAddPersistence(int num, int count) {
String numStr = String.valueOf(num);
if (numStr.length() == 1) {
return count;
}

int newNum = 0;
for (char c : numStr.toCharArray()) {
newNum += Integer.valueOf(String.valueOf(c));
}
return getAddPersistence(newNum, ++count);
}

public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
AdditivePersistence c = new AdditivePersistence();
System.out.print(c.AdditivePersistence(2718));
}
}

Additive Persistence Javascript

function AdditivePersistence(num) {

let str = String(num); //number into string
let arr = str.split(""); //string into array
// adds numbers in array, then repeats until left with single digit
let count = 0;
while (arr.length > 1) {
// set `arr` to string then array with values returned from `.reduce()`
arr = String(arr.reduce(function(a, b) {
return Number(a) + Number(b)
})).split("");
count++;
}

return count;

};

var n = AdditivePersistence(2718);
console.log(n);

Additive Persistence Python

def AdditivePersistence(num):
steps = 0
while num > 9:
snum = str(num)
sdigits = list(snum)
digits = [int(x) for x in sdigits]
num = sum(digits)
steps = steps + 1
return steps

# keep this function call here
# to see how to enter arguments in Python scroll down
print AdditivePersistence(raw_input())

### Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Our website uses cookies to enhance your experience. Learn More
Accept !