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);
}
}
}
NYOJ-题目(Math)--105--------------------------------九的余数
最新推荐文章于 2018-11-17 02:10:41 发布