看起来我在这里正确回答了这个问题: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);
}发布于 2019-09-17 23:57:24
我只是使用自己开发的另一种方法找到了解决方案。我基本上使用了嵌套的三元运算符。希望它能在你的学习过程中对你有所帮助和支持。
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;
}https://stackoverflow.com/questions/41001578
复制相似问题