close
題目概要:
把所有數字加總。Ex 12345=1+2+3 +4+5=15 ,15=1+5=6。
解題方向:
用字串讀取輸入,在一個一個字元相加。
程式碼:
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 uva11332{ | |
public static void main(String args[]){ | |
Scanner sc=new Scanner(System.in); | |
while(sc.hasNext()){ | |
String st=sc.next(); | |
if(st.equals("0")) break; | |
//字元相加,加到st長度只有1為止(只有個位數)。 | |
int num=0; | |
while(st.length()!=1){ | |
for(int i=0;i<st.length();i++){ | |
num=num+st.charAt(i)-48; | |
} | |
st=Integer.toString(num); | |
num=0; | |
} | |
//Output | |
System.out.println(st); | |
} | |
} | |
} |
文章標籤
全站熱搜