描述:
写一个persistence()方法,将一个长整数n的每位数不断相乘,直到得到单个数字,返回相乘的次数。
例如:
persistence(39) == 3 // 因为 3*9 = 27, 2*7 = 14, 1*4=4
// 并且4是单个数字
persistence(999) == 4 // 因为 9*9*9 = 729, 7*2*9 = 126,
// 1*2*6 = 12, 1*2 = 2
persistence(4) == 0 // 因为4本身就是单个数字
MyCode:
using System;
public class Persist
{
public static int Persistence(long n)
{
int count = 0;//声明要返回的次数
while(n > 9)
{
int x = 1;
string str = n.ToString();//转化n为字符串,赋给str
int[] arr = new int[str.Length];
for(int j = 0;j < str.Length;j++)//用for循环给数组赋值
{
arr[j] = str[j] - 48;//利用ASCII码char转int => "0" - 48 = 0
}
foreach(int i in arr)//遍历数组,位数相乘
{
x = x * i;
n = x;
}
count++;
}
return count;
}
}
CodeWar:
using System.Linq;
public class Persist
{
public static int Persistence(long n)
{
long nF = n.ToString().Aggregate(1,(a,b) => a * (b - '0'));
return n < 9 ? 0 : 1 + Persistence(nF);
}
}