水仙花數

水仙花數是這樣的:一個數的各個位數上的數字的立方和等於本身。

思路:

i_f24.gif 將給出的數字拆分,並將結果放在一個整型數組中

i_f24.gif將上一步的整型數組中的每一個元素立方

i_f24.gif 將立方後的數與給出的數比較,是否相等,若相等就是水仙花數

很容易實現:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 100; i < 1000; i++)
            {
                int[] ary = GetAry(i);
                int temp = GetCubic(ary);
                if (temp==i)
                {
                    Console.WriteLine(i);
                }
            }
        }
        /// <summary>
        /// 將數字拆分到一個數組中
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        public static int [] GetAry(int i)
        {
            int index = 0;
            int[] ary = new int[3];
            while (i > 0)
            {
                ary[index] = i % 10;
                i = i / 10;
                index++;
            }
            return ary;
        }
        /// <summary>
        /// 得到拆分數組中每一位數的立方
        /// </summary>
        /// <param name="ary"></param>
        /// <returns></returns>
        public static int GetCubic(int[] ary)
        {
            int temp=0;
            for (int i = 0; i <ary.Length ; i++)
            {
                temp+=(ary[i]*ary[i]*ary[i]);
            }
            return temp;
        }
    }
}

老夫子說:溫故而知新!

j_0047.gifAjax的姑娘,加油!j_0047.gif


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章