gpt4 book ai didi

java - 从 int 中提取偶数位

转载 作者:行者123 更新时间:2023-11-29 03:10:04 25 4
gpt4 key购买 nike

这是 problem我正在解决。

Write a method evenDigits that accepts an integer parameter n and that returns the integer formed by removing the odd digits from n. The following table shows several calls and their expected return values:

Call    Valued Returned
evenDigits(8342116); 8426
evenDigits(4109); 40
evenDigits(8); 8
evenDigits(-34512); -42
evenDigits(-163505); -60
evenDigits(3052); 2
evenDigits(7010496); 46
evenDigits(35179); 0
evenDigits(5307); 0
evenDigits(7); 0

如果传递给该方法的偶数位不是 0 的负数,结果也应该是负数,如上图传递 -34512 时所示。

应忽略结果中的前导零,如果数字中除 0 外没有偶数位,则该方法应返回 0,如最后三个输出所示。

到目前为止我有这个 -

public static int evenDigits(int n) {
    if (n != 0) { 
        int new_x = 0;
int temp = 0;
String subS = "";
    String x_str = Integer.toString(n);
if (x_str.substring(0, 1).equals("-")) {
 temp = Integer.parseInt(x_str.substring(0, 2));
 subS = x_str.substring(2);
} else {
 temp = Integer.parseInt(x_str.substring(0, 1));
 subS = x_str.substring(1);
}

        if (subS.length() != 0) {
             new_x = Integer.parseInt(x_str.substring(1));
        }
        
        if (temp % 2 == 0) {
             return Integer.parseInt((Integer.toString(temp) + evenDigits(new_x)));
        } else {
            return evenDigits(new_x);
        }
    }
return 0;
}

最佳答案

为什么人们似乎总是想转换成String来处理数字? Java 具有非常好的算术原语来处理这项工作。例如:

public static int evenDigits(int n) {
int rev = 0;
int digitCount = 0;

// handle negative arguments
if (n < 0) return -evenDigits(-n);

// Extract the even digits to variable rev
while (n != 0) {
if (n % 2 == 0) {
rev = rev * 10 + n % 10;
digitCount += 1;
}
n /= 10;
}

// The digits were extracted in reverse order; reverse them again
while (digitCount > 0) {
n = n * 10 + rev % 10;
rev /= 10;
digitCount -= 1;
}

// The result is in n
return n;
}

虽然这对于像本例这样的简单学术练习没有影响,但预计仅通过算术处理作业会比涉及转换为 String 的任何操作执行得更好。

关于java - 从 int 中提取偶数位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29872298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com