看起来我在这里正确回答了问题:http://codingbat.com/prob/p186753
但是我的代码对我来说似乎太长了而且没有得到很好的优化。任何人都可以建议我可以做些什么来使我的代码更简洁?这是我的代码:
public int roundSum(int a, int b, int c) {
return round10(a) + round10(b) + round10(c);
}
public int round10(int n) {
String sumStr = null;
if (n % 10 < 5) {
int left = n / 10;
String leftStr = Integer.toString(left);
sumStr = leftStr + "0";
}
if (n % 10 >= 5) {
int left = n / 10;
int leftNew = left + 1;
String sum = Integer.toString(leftNew);
sumStr = sum + "0";
}
return Integer.parseInt(sumStr);
}
答案 0 :(得分:0)
我刚刚使用自己开发的另一种方法找到了解决方案。我基本上使用了嵌套三元运算符。希望它会对您的学习过程有所帮助并为您提供支持。
public int roundSum(int a, int b, int c) {
a = (a % 10 < 5 ) ? (a / 10) * 10 : ((a / 10) + 1) * 10;
b = (b % 10 < 5 ) ? (b / 10) * 10 : ((b / 10) + 1) * 10;
c = (c % 10 < 5 ) ? (c / 10) * 10 : ((c / 10) + 1) * 10;
return a+b+c;
}