[英]How can I find a specific digit in the square root of 2 in java?
我的代碼有問題。 我無法舉例說明為什么它不起作用,因為它是一個“隱藏測試”,但我可以說代碼 100% 適用於 0-6 的數字,因為其他測試用例就是這樣。 代碼應該做的是返回輸入到參數中的索引的數字。 例如,如果 digit 等於 0,則程序將 output 1,這是 sqrt(2) 的第一個數字。 如果他們輸入 1,它將是 4,因為 sqrt(2) 是 1.4
public static int sqrtTwo(int digit)
{
if (digit < 0)
{
return -1;
}
double two = Math.sqrt(2);
/* option 1
//return (int)((Math.pow(10, digit) * two) - ((int)(Math.pow(10, digit - 1)*two))*10);
*/
//option 2
String s = Double.toString(two);
s = s.substring(0, 1) + s.substring(2);
return (int)(Double.parseDouble(s.substring(digit, digit + 1)));
}
您的主要問題是雙精度。 最好的方法是遷移到更精確的類型,例如 BigDecimal。
public static int sqrtTwo(int digit) {
if (digit < 0) {
return -1;
}
MathContext context = new MathContext(Math.max(digit+1, 1));
BigDecimal two = BigDecimal.valueOf(2L).sqrt(context); // compute the decimal with any precision matching your digit index
String s = two.toString();
s = s.charAt(0) + s.substring(2); // I assume this part removes the separator character
return Integer.parseInt(s.substring(digit, digit + 1));
}
這將返回 SQRT(2) 的第 n 個數字。
第二個改進是將數字解析為 Integer,而不是在中間使用 Double。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.