2014년 11월 12일 수요일

[Java] Armstrong Number 구하기

Armstrong number  란? 수의 각 자릿수의 숫자 값을 ^3을 한뒤 더한값이 원래의 수와 같은 수를 말한다.
ex)
153 은 (1*1*1)+(5*5*5)+(3*3*3) = 153
371 은 (3*3*3)+(7*7*7)+(1*1*1) = 371
 
입력한 값이 Armstrong number 인지 아닌지 판별하기 위한 프로그램 구현하시오.

  1. public class Armstrong {
  2.     public boolean isArmstrong(int number){
  3.     }
  4.    
  5.     public static void main(String[] args){
  6.         Armstrong armstrong = new Armstrong();
  7.         // 코드 구현
  8.     }
  9. }

  1. public class Armstrong {
  2. public boolean isArmstrong(int number){
  3.  
  4. int result = 0;
  5. int x = number;
  6. while(number != 0){
  7. int y = number%10;
  8. result = result + y*y*y;
  9. number = number/10;
  10. }
  11. //number is Armstrong return true
  12. if(x == result){
  13. return true;
  14. }
  15.  
  16. return false;
  17. }
  18.  
  19. }
세제곱 이상의 함수일때 다음의 제곱 함수를 사용한다.

  1. while(number != 0){
  2. int y = number%10;
  3. result = result+(int)Math.pow(y, 3);
  4. number = number/10;
  5. }

댓글 없음:

댓글 쓰기