a040. 阿姆斯壯數
阿姆斯壯數有好多名字,我聽過的是水仙花數。
其特徵就是長度n位的數,各位數的n次方總和等於自身,例如115 = 1^3 + 1^3 + 5^3
解題想法:
寫一個方法(method)來判斷一數是否為水仙花數,是回傳true,不是就回傳false。
方法內容是先將整數換成字串再換成字元陣列方便對各位數計算,for迴圈之中使用之前用過得Character.getNumericValue。
程式碼如下:
- /* a040. 阿姆斯壯數
- *
- * 2020/3/2
- */
- import java.util.Scanner;
- public class Pa040{
- public static void main(String[] args){
- Scanner scanner = new Scanner(System.in);
- while(scanner.hasNext()){
- int n = scanner.nextInt();
- int m = scanner.nextInt();
- boolean none = true;
- for(; n <= m; n++){
- if(isNarcissistic(n)){
- System.out.print(n + " ");
- none = false;
- }
- }
- System.out.println(none? "none": "");
- }
- }
- public static boolean isNarcissistic(int num){
- char[] nums = Integer.toString(num).toCharArray();
- int sum = 0;
- for(char ch: nums){
- sum += (int)Math.pow(Character.getNumericValue(ch), nums.length);
- }
- return num == sum;
- }
- }
沒有留言:
張貼留言