2016年7月4日 星期一

Q11332: Summing Digits


https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&category=&problem=2307&mosmsg=Submission+received+with+ID+17617814
方法一
import java.util.*;

public class Main {

 public static void main(String[] args) {
  Scanner scn = new Scanner(System.in);
  while(scn.hasNext()){
   String str=scn.next();
   if(str.equals("0"))break;
   int tot=0;
   while(true){
    String arr[]=str.split("");
    if(arr.length==1){
     tot=Integer.parseInt(arr[0]);
     break;
    }
    tot=0;
    for(int i=0;i&ltarr.length;i++){
     tot+=Integer.parseInt(arr[i]);
    }
    str=Integer.toString(tot);
   }
   System.out.println(tot);
  }
 }

 /* 
    題目:Q11332: Summing Digits 
    作者:1010
    時間:西元 2016 年 7 月 */
}

方法二
import java.util.*;

public class Main {

 public static void main(String[] args) {
  Scanner scn = new Scanner(System.in);
  while (scn.hasNext()) {
   int n = scn.nextInt();
   if (n == 0)
    break;
   while (n / 10 != 0) {
    n = n % 10 + n / 10;
   }
   System.out.println(n);
  }
 }
 /* 
    題目:Q11332: Summing Digits
    作者:1010
    時間:西元 2016 年 7 月 */

}


困難度 
這題是我當初參加CPE的第一題,這題我是利用字串去解當長度為1時跳出迴圈,還要注意當數入個位數時要直接輸出

沒有留言:

張貼留言