新手求助,数字拆分并且运算的写法
我刚学C#,遇到个标签码的运算问题,求各位高手帮忙解答,具体内容如下:随意输入一串数字:sum=4789(不固定的)
然后先进行第一步运算:a=4*4+7*7+8*8+9*9
=16+49+64+81
=210
也就是先拆分成单个数字,然后乘以自己,相加得到一个数210
接着判断位数,如果不是1位的话就进行下一步运算:
210=2+1+0=3
最后输出b=3
也就是输入4789,输出结果是3.
请高手指教,谢谢
/// <summary> /// 入口,传入要处理的数字(下面的方法中,如果不能满足数字的大小,就换成float或者是double) /// </summary> /// <param name="NO"></param> /// <returns></returns> private int PNum(int NO) { if (NO.ToString().Length == 1) //一位数字 { return NO; } else { int ResNo = MulNo(NO); if (ResNo.ToString().Length == 1) { return ResNo; } else { return AddNo(ResNo); } } } /// <summary> /// 每位相乘 /// </summary> /// <param name="NO"></param> /// <returns></returns> private int MulNo(int NO) { int Res = 0; char[] noList = NO.ToString().ToCharArray(); foreach (char c in noList) { Res += int.Parse(c.ToString()) * int.Parse(c.ToString()); } return Res; } /// <summary> /// 每位相加 /// </summary> /// <param name="NO"></param> /// <returns></returns> private int AddNo(int NO) { int Res = 0; char[] noList = NO.ToString().ToCharArray(); foreach (char c in noList) { Res += int.Parse(c.ToString()); } return Res; }
using System; using System.Collections.Generic; namespace GeiSB { class Program { static void Main(string[] args) { Console.WriteLine("Please enter the number:"); string numberStr = Console.ReadLine(); List<int> _getNumbers = new List<int>(); _getNumbers = GetEveryBit(numberStr); long firstSetupResult = 0; foreach (int i in _getNumbers) { firstSetupResult += i * i; } Console.WriteLine(firstSetupResult.ToString()); List<int> _getNumbers_2 = new List<int>(); _getNumbers_2 = GetEveryBit(firstSetupResult.ToString()); int endResult = 0; foreach (int i in _getNumbers_2) { endResult += i; } Console.WriteLine(endResult.ToString()); Console.ReadKey(); } public static List<int> GetEveryBit(string NumberStr) { char[] numberArray = NumberStr.ToCharArray(); List<int> numbers = new List<int>(); foreach (char num in numberArray) { numbers.Add(Convert.ToInt32(num.ToString())); } return numbers; } } }