题目
以零结尾的数字很无聊。
他们可能在你的世界里很有趣,但不是在这里。
在结果里摆脱它们。
1450 -> 145
960000 -> 96
1050 -> 105
-1050 -> -105
单独零是好的,不要担心。
测试用例
import static org.junit.Assert.*;
import org.junit.Test;
public class NoBoringTest {
private static void testing(int actual, int expected) {
assertEquals(expected, actual);
}
@Test
public void test1() {
System.out.println("Fixed Tests: noBoringZeros");
testing(NoBoring.noBoringZeros(1450), 145);
testing(NoBoring.noBoringZeros(960000), 96);
testing(NoBoring.noBoringZeros(1050), 105);
testing(NoBoring.noBoringZeros(-1050), -105);
}
}
解题
My
public class NoBoring {
public static int noBoringZeros(int n) {
if (n==0) {
return n;
}
char[] charArray = Integer.toString(n).toCharArray();
int count = 0;
for (int i = charArray.length-1; i >= 0; i--) {
if (charArray[i] == 48) {
count++;
} else {
break;
}
}
return Integer.valueOf((new String(charArray)).substring(0,charArray.length-count));
}
}
Other
public class NoBoring {
public static int noBoringZeros(int n) {
if (n == 0)
return n;
while (n % 10 == 0)
n /= 10;
return n;
}
}
public class NoBoring {
public static int noBoringZeros(int n) {
if (n == 0) return 0;
if (n % 10 != 0) return n;
else return noBoringZeros (n / 10);
}
}
public class NoBoring {
public static int noBoringZeros(int n) {
// your code
return n == 0 || n % 10 != 0 ? n : noBoringZeros(n/10);
}
}
public class NoBoring {
public static int noBoringZeros(int n) {
while (n % 10 == 0 && n != 0) n/=10;
return n;
}
}
后记
看到别人 的解题,我都惊呆了,还可以这么简单的解,唉。