您的位置:首页 > 其它

NYOJ-题目(Math)--105--------------------------------九的余数

2015-03-27 10:17 417 查看
http://acm.nyist.net/JudgeOnline/problem.php?pid=105

 package org.acm.math;

/*http://acm.nyist.net/JudgeOnline/problem.php?pid=105*/
//网上看的方法:每一位的数都加起来,再对9取模,这么做赶脚不对,但事实上AC了
/*
* 还有另一个方法,就是比如输入一个数123456789
* 设sum = 0;
* sum = (sum *10 + 1) % 9
* sum = (sum *10 + 2) % 9
* sum = (sum *10 + 3) % 9
* ....
* sum = (sum *10 + 9) % 9
* 最后输出sum即可
* */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Math_105 {

public static void main(String[] args) throws IOException {

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

int t = Integer.parseInt(br.readLine());
while (t-- > 0) {
String str = br.readLine();
long sum = 0;
for (int i = 0; i < str.length(); i++)
sum += str.charAt(i) - '0';
System.out.println(sum % 9);
}
}
}

方法2:
<pre name="code" class="java">import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;

public class Math_105 {

private static BigInteger TEN = BigInteger.valueOf(10);
private static BigInteger MOD = BigInteger.valueOf(9);

public static void main(String[] args) throws IOException {

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

int t = Integer.parseInt(br.readLine());
while (t-- > 0) {
String str = br.readLine();
BigInteger sum = BigInteger.ZERO;
for (int i = 0; i < str.length(); i++) {
sum = (sum.multiply(TEN).add(BigInteger.valueOf(str.charAt(i) - '0'))).mod(MOD);
}
System.out.println(sum);
}
}
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  nyoj105