当处理大数值构造(如"100...001")时,直接拼接字符串安全可靠,而用math.pow(10, n-1) + 1转为整数再输出会导致溢出或精度丢失,尤其在n较大时引发运行时错误或答案错误。
在 CodeChef 题目 ZOOZ 中,要求对每个测试用例输出一个长度为 n 的二进制风格字符串:首尾为 '1',中间全为 '0'(例如 n=4 → "1001",n=3 → "101")。表面看,以下两种实现似乎等价:
✅ CODE 1(正确):逐字符构建并打印字符串
int t = in.nextInt();
while ((t--) > 0) {
int n = in.nextInt();
for (int j = 0; j < n; j++) {
if (j == 0 || j == n - 1)
System.out.print("1");
else
System.out.print("0");
}
System.out.println(); // 推荐用 println() 替代 print("\n"),更清晰
}❌ CODE 2(错误):试图用数学表达式生成整数再输出
int t = in.nextInt();
while ((t--) > 0) {
int n = in.nextInt();
System.out.println((int) Math.pow(10, n - 1) + 1);
}根本原因并非“输出内容不同”,而是类型与语义的错位:
'1';? 验证示例(n = 17):
System.out.println((int) Math.pow(10, 16) + 1); // 实际输出:10000000000000001?错! // 真实结果(Java 中):-2147483648(因溢出后取模)
该行为导致答案完全错误,且 Math.pow 对大指数的 double 近似本身就不具备整数精度保障。
✅ 正确替代方案(若坚持数值逻辑):
仅适用于小 n(≤18),且必须用 BigInteger:
import java.math.BigInteger; // ... BigInteger ten = BigInteger.TEN; BigInteger res = ten.pow(n - 1).add(BigInteger.ONE); System.out.println(res);
但此方案时间/空间开销远高于字符串构造,且违背题意“构造字符串”的本质。
? 总结与最佳实践:
因此,CODE 1 成功是因其符合问题本质(字符串构造),而 CODE 2 失败源于数值溢出、浮点误差与类型误用——不是“逻辑等价”,而是“表象巧合,底层崩坏”。