2020年3月2日 星期一

[zerojudge]a040. 阿姆斯壯數

a040. 阿姆斯壯數

阿姆斯壯數有好多名字,我聽過的是水仙花數
其特徵就是長度n位的數,各位數的n次方總和等於自身,例如115 = 1^3 + 1^3 + 5^3

解題想法:
寫一個方法(method)來判斷一數是否為水仙花數,是回傳true,不是就回傳false。
方法內容是先將整數換成字串再換成字元陣列方便對各位數計算,for迴圈之中使用之前用過得Character.getNumericValue。

程式碼如下:

  1. /* a040. 阿姆斯壯數
  2. *
  3. * 2020/3/2
  4. */
  5.  
  6. import java.util.Scanner;
  7.  
  8. public class Pa040{
  9.  
  10. public static void main(String[] args){
  11. Scanner scanner = new Scanner(System.in);
  12.  
  13. while(scanner.hasNext()){
  14. int n = scanner.nextInt();
  15. int m = scanner.nextInt();
  16.  
  17. boolean none = true;
  18.  
  19. for(; n <= m; n++){
  20. if(isNarcissistic(n)){
  21. System.out.print(n + " ");
  22. none = false;
  23. }
  24. }
  25.  
  26. System.out.println(none? "none": "");
  27. }
  28. }
  29.  
  30. public static boolean isNarcissistic(int num){
  31. char[] nums = Integer.toString(num).toCharArray();
  32.  
  33. int sum = 0;
  34.  
  35. for(char ch: nums){
  36. sum += (int)Math.pow(Character.getNumericValue(ch), nums.length);
  37. }
  38.  
  39. return num == sum;
  40. }
  41. }

沒有留言:

張貼留言