这是一道简单的算法题,主要就是用了取整(/)和求余(%)这两个基本运算
C#代码如下所示:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace SumFormula { class Program { static void Main(string[] args) { try { Console.WriteLine("Please enter a value."); int value = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("The original value is: " + value + ""); //循环处理输入的数值 while (true) { EvaluationArithmetic(value); Console.WriteLine("Please enter a value.[If you want to exit, please enter 'e'.]"); value = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("The original value is: " + value + ""); if (value.ToString().Equals("e", StringComparison.CurrentCultureIgnoreCase)) { break; } } } catch (Exception ex) { } } ///<summary> /// 算法 ///</summary> ///<param name="value">传入用户输入的数值</param> private static void EvaluationArithmetic(int value) { try { //标示是否找到最终的数值(找到为true,没找到为false) bool flagFindFinalValue = false; int currentValue = value; string currentValueStr = value.ToString(); int count = currentValueStr.Length; while (currentValue > -1) { int finalValue = GetFinalVlue(value, currentValue, count); if (finalValue == value) { flagFindFinalValue = true; Console.WriteLine("The final value is: " + currentValue.ToString() + "\n\n"); break; } else { //如果没找到数值减1,继续循环 currentValue--; count = currentValue.ToString().Length; //如果此时的数值 + 位数 * 9 小于原始的Value,那么循环结束(即没有找到相应的数值),提高效率。 if (currentValue + count * 9 < value) { break; } } } if (flagFindFinalValue == false) { Console.WriteLine("Sorry, cann't find the final value.\n\n"); } } catch (Exception ex) { } } //将此时传入的数值进行分解,返回此数值与其各个位上的数字之和 private static int GetFinalVlue(int originalValue, int value, int digit) { try { int currentValue = value; int currentDigit = digit; int totalEachDigitValue = 0; for(int i = currentDigit; i > 0; i--) { int hightestDigitValue = currentValue / Convert.ToInt32(Math.Pow(10, i - 1)); int remainderValue = currentValue % Convert.ToInt32(Math.Pow(10, i - 1)); totalEachDigitValue += hightestDigitValue; currentValue = remainderValue; } return totalEachDigitValue + value ; } catch (Exception ex) { return -1; } } } }