求100到999之間水仙花的個數,100999水仙花個數

來源:互聯網
上載者:User

求100到999之間水仙花的個數,100999水仙花個數

   

    題目:列印出所有的 水仙花數 ,所謂 水仙花數 是指一個三位元,其各位元字立方和等於該數本身。

    例如:153是一個 水仙花數 ,因為153=1的三次方+5的三次方+3的三次方。


public static void main(String[] args) {System.out.println(Arrays.toString(getNarcissisticNumber(100, 999)));  }/** * 列印出所有的 水仙花數 ,所謂 水仙花數 是指一個三位元,其各位元字立方和等於該數本身。 * 例如:153是一個 水仙花數 ,因為153=1的三次方+5的三次方+3的三次方。 * @param start * @param end * @return */public static int[] getNarcissisticNumber(int start, int end) {// 定義結果數組,用於儲存符合規則的數字int[] arr = new int[end-start];// index 作為計數器,記錄arr數組中存入的元素的個數int index = 0;// 定義數組,分別儲存數位百位,十位,各位int[] args = new int[3];for (int i=start; i < end; i++) {args[0] = i / 100;args[1] = i % 100 / 10;args[2] = i % 100 % 10;// 計算數字各位元的立方和// double sum = Math.pow(args[0], 3) + Math.pow(args[1], 3) + Math.pow(args[2], 3);int sum = args[0] * args[0] * args[0] + args[1] * args[1] * args[1] + args[2] * args[2] * args[2];// 判斷各位元立方和是否等於當前數字if (sum == i) {arr[index] = i;index++;}}// 將存入的水仙花數量拷貝出來,剔除那些初始的0return Arrays.copyOf(arr, index);}


一個變形的寫法,定義方法,判斷數字是否是水仙花數字

/**  * 判斷該數字是否是水仙花數字  * @param num 入參數字  * @return true 是水仙花數字;false 不是  */public static boolean isNarcissisticNumber(int num) {// 定義數組,分別儲存數位百位,十位,各位int[] args = new int[3];args[0] = num / 100;args[1] = num % 100 / 10;args[2] = num % 100 % 10;// 計算數字各位元的立方和int sum = args[0] * args[0] * args[0] + args[1] * args[1] * args[1] + args[2] * args[2] * args[2];return sum == num;}



在方法中調用isNarcissisticNumber(int num) 方法

public static void main(String[] args) {for (int i=100; i<=999; i++) {if (isNarcissisticNumber(i)) {System.out.println(i);}}}




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.