有没有能写出的

qq_45808024 2020-01-04 03:30:49
求出10000以下符合条件的自然数。条件是:千位数字与百位数字之和等于十位数字与个位数字之和,且千位数字与百位数字之和等于个位数字与千位数字之差的10倍。计算并输出这些四位自然数的个数cn以及这些数的和sum。
...全文
25 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
HerryDong 2020-01-04
  • 打赏
  • 举报
回复
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int sum = 0;
            int count = 0;
            for (int i = 1000; i < 10000; i++)
            {
                if (Validate(i))
                {
                    sum += i;
                    count++;
                }
            }
            Console.WriteLine("满足条件的四位自然数的个数为:{0}", count);
            Console.WriteLine("满足条件的四位自然数的和为:{0}", sum);
            Console.ReadKey(true);
        }

        static bool Validate(int num)
        {
            int a = num % 10;          // 个位数
            int b = num / 10 % 10;     // 十位数
            int c = num / 100 % 10;    // 百位数
            int d = num / 1000;        // 千位数
            if (a + b == c + d && c + d == 10 * (a - d))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
纯粹个人爱好 2020-01-04
  • 打赏
  • 举报
回复
假设四位数是abcd,由条件有a+b=c+d,a+b=10*(d-a),可以得到c和d关于a,b的表达式,10*d=11*a+b,c=a+b-d,注意到0<=d<=9,0<=c<=9且c,d都是整数,因此两个循环就可以解决问题了。
int a,b,c,d;
List<int> result = new List<int>();
for(a=1;a<=9;a++)
{
for(b=0;b<=9;b++)
{
d=(11*a+b)/10;
if((10*d)!=(11*a+b)) continue;
if(d>9) continue;
c=a+b-d;
if(c<0||c>9) continue;
result.Add(1000*a+100*b+10*c+d);
}
}
cn=result.Count;
sum = ((int[])(result.ToArray())).Sum();

110,825

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧