简体   繁体   English

将数字中的偶数数字更改为奇数

[英]Changing even digits in a number to odd

I am trying to pick the even digits from a number and convert them to odd by adding 1 to it 我正在尝试从数字中选择偶数数字,并将其加1转换为奇数

example input/output 输入/输出示例

n = 258463, ans = 359573 n = 258463,ans = 359573

    int n=26540;
    System.out.println("n= "+n+", ans= "+even2odd(n));
    n=9528;
    System.out.println("n= "+n+", ans= "+even2odd(n));

public static int even2odd(int n)
{

while ( n > 0 ) {
    if (n%2==0) {
        n +=1;
    }
    System.out.print( n % 10);
    n = n / 10;
}
int ans = n;

return ans; 
}

as you can see right I managed to convert all the even digits to odd but i dont know how to reverse them back into order and output it in the right place 如您所见,我设法将所有偶数都转换为奇数,但我不知道如何将它们反转回顺序并在正确的位置输出

Aaaaaannnd一班轮到这里

int i = Integer.parseInt(Integer.toString(26540).replaceAll("2", "3").replaceAll("4", "5").replaceAll("6", "7").replaceAll("8", "9"));

You can do this: 你可以这样做:

public static int even2odd(int n)
{
    StringBuilder result = new StringBuilder();
    while(n > 0)
    {
        int firstDigit = n %10;

        if(firstDigit%2==0)
            ++firstDigit;
        result.append(firstDigit);

        n = n/10;
    }       
    return Integer.parseInt(result.reverse().toString());
}

How about: 怎么样:

String numString = n+"";
String outString = "";
for(int i=0; i<numString.length;i++){
   int digit = Character.getNumericValue(numString.charAt(i));
   if(digit%2==0) digit++;
   outString+=digit;
}
int out = Integer.parseInt(outString);

If you are instructed not to use String or Integer. 如果指示您不要使用String或Integer。

public static int even2odd(int n) { 
    int ans = 0;
    int place = 1;

    while ( n > 0 ) {
         if (n%2==0) {
              n +=1;
         }

         ans = ans+((n%10)*place);
         place = place*10;
         n = n / 10;
    }

    System.out.print( ans);

    return ans;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM