【问题标题】:Integer square digit by digit整数平方位数
【发布时间】:2016-07-07 12:09:03
【问题描述】:

应该有一个程序,它将整数的每个数字平方,然后将这些临时数字连接成一个新的整数。 我已经编写了一个代码,它可以解决我的测试用例的问题,但是自动测试器会为一些随机生成的输入数字提供错误。

public class SquareDigit {
  public int squareDigits(int n) {
    int tmp = 0;
    String returnvalue="";

    while(n > 0) {
        tmp = n % 10;
        tmp = tmp * tmp;
        returnvalue = returnvalue + Integer.toString(tmp);
        n /= 10;
    }       
    int result=Integer.parseInt(returnvalue);

    return result;
  }
}

【问题讨论】:

  • 问题可能是由于整数精度,使用 long 或 BigInteger
  • @Sanjeev 猜这是因为 Integeroverflow。

标签: java square


【解决方案1】:

使用大整数。 BigInteger 是一个以任意精度保存整数的类:

不可变的任意精度整数。

当对一个数字进行平方超过int 类型的最大可用范围时,您的代码会出错。如果您在long 范围内的范围内进行测试,long 可以解决问题。 BigInteger 适用于任何整数。


代码应该类似于:

public  BigInteger squareDigits(int n) {
    BigInteger tmp = null;
    String returnvalue = "";

    while (n > 0) {
        tmp = BigInteger.valueOf(n % 10);
        tmp = tmp.pow(2);
        returnvalue = returnvalue + String.valueOf(tmp);
        n /= 10;
    }       

    return new BigInteger(returnvalue);
  }


  ...

  System.out.println(squareDigits(123456789));  // Print 816449362516941

【讨论】:

  • 需要导入java.math.BigInteger;
  • 我已经导入了,但它是一个测试环境,所以可能会导致导入问题。
  • 没有没有问题。您需要在显式使用它的每个类中导入 BigInteger。
  • @KovacsAkos BigInteger tmp = 0;,您不能将int 分配给BigInteger,使用它的构造函数。
  • 查看更新后的答案。您将看到如何构造 BigInteger 以及如何制作正方形。
【解决方案2】:

使用

returnvalue = Integer.toString(tmp) + returnvalue;

而不是

returnvalue = returnvalue + Integer.toString(tmp);

您从后到前迭代数字,例如对于输入123,中间结果应该是

  • "9"
  • "49"
  • "149"

但在你的代码中是

  • "9"
  • "94"
  • "941"

【讨论】:

  • 这真的很有趣,因为它使用预定义的测试值。谢谢!
猜你喜欢
  • 1970-01-01
  • 2015-03-04
  • 1970-01-01
  • 2012-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-26
  • 1970-01-01
相关资源
最近更新 更多