简体   繁体   中英

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

example input/output

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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