close
題目概要:
如果是9的倍數,請找出degree為多少。
解題方向:
1. 輸入的數字有1000位數,所以無法用數字處理,需要用字串。
2. 設輸入數字為999,則degree為2。
(1)9+9+9=27
(2)2+7=9
程式碼:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Java | |
import java.util.Scanner; | |
class uva10922{ | |
public static void main(String args[]){ | |
Scanner sc=new Scanner(System.in); | |
while(sc.hasNext()){ | |
String st=sc.next(); | |
//當輸入為0時終止程式。 | |
if(st.equals("0"))break; | |
/* | |
計算有多少degree(9倍數判斷方法:全部數字相加為9倍數)。 | |
Ex 999 degree=2 | |
1. 9+9+9=27 | |
2. 2+7=9 | |
*/ | |
int count=0; | |
String temp=st; | |
while(true){ | |
int total=0; | |
for(int i=0;i<temp.length();i++){ | |
total=total+temp.charAt(i)-48; | |
} | |
if(total%9==0){ | |
count++; | |
if(total==9) break; | |
else temp=Integer.toString(total); | |
}else{ | |
break; | |
} | |
} | |
//結果輸出。 | |
if(count!=0) System.out.println(st+" is a multiple of 9 and has 9-degree "+count+"."); | |
else System.out.println(st+" is not a multiple of 9."); | |
} | |
} | |
} |
文章標籤
全站熱搜