水仙花數是這樣的:一個數的各個位數上的數字的立方和等於本身。
思路:
很容易實現:
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; } } }
老夫子說:溫故而知新!