0

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

John Smith
  • 1
  • 1
  • 2
  • 1
    Won't your method always return 0? Your loop goes until `n>0` so when `n=0` the loop exits and you return it. – Atri Feb 23 '16 at 22:07
  • add each one to a list or something. you can also just assign the whole number to another variable and just reverse the order of the digits. – Jay T. Feb 23 '16 at 22:11
  • Can you please elaborate on your example input, what is the process of n = 258463 getting turned into ans = 359573 – mrhn Feb 23 '16 at 22:13
  • @MartinHenriksen lets say the user inputs the number 258463 I want to turn all the even numbers in that digit to odd. So hen the user inputs that number i would output 359573 – John Smith Feb 23 '16 at 22:16

4 Answers4

3

Aaaaaannnd one liner goes here

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

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());
}
gsamaras
  • 71,951
  • 46
  • 188
  • 305
0

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);
0

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;
}
Johan
  • 74,508
  • 24
  • 191
  • 319