• 已知一个整数N,求另外一个整数M,使得M本身 + M各个位上的数 = N


    这是一道简单的算法题,主要就是用了取整(/)和求余(%)这两个基本运算

    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;
    }
    }
    }
    }

    。。。

  • 相关阅读:
    1040 最大公约数之和(欧拉函数)
    1028 大数乘法 V2(FFT or py)
    1020 逆序排列(DP)
    1837 砝码称重
    1070 Bash游戏 V4
    1280 前缀后缀集合(map)
    1390 游戏得分(贪心)
    1179 最大的最大公约数
    1400 序列分解(dfs)
    1420 数袋鼠好有趣(贪心二分)
  • 原文地址:https://www.cnblogs.com/mingmingruyuedlut/p/2212270.html
Copyright © 2020-2023  润新知