位数相乘

描述:

写一个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);
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值