Replace all 0's with 5 || i wrote code but its not working expected| o/p is in reverse order

1.1k views Asked by At

Problem: Given a number N. The task is to complete the function convertFive() which replace all zeros in the number with 5 my code| plz validate any help me

public class Replaceall0swith5 {
    public static void convertFive(int n) {
    //add code here.
        int digit, sum = 0;
        while (n > 0) {
            digit = n % 10;
            if (digit == 0) {
                digit = 5;
            }
            sum = sum * 10 + digit;
            n = n / 10;
        }
        System.out.print(n + " All O's replaced with 5 " + sum);
    }

    public static void main(String[] args) {
        Replaceall0swith5.convertFive(1004);
    }
}
3

There are 3 answers

1
AudioBubble On BEST ANSWER

Try this.

public static void convertFive(int n) {
    int sum = 0;
    for (int rank = 1; n > 0; n = n / 10, rank *= 10) {
        int digit = n % 10;
        if (digit == 0)
            digit = 5;
        sum = sum + digit * rank;
    }
    System.out.print(n + " All O's replaced with 5 " + sum);
}
n digit rank sum
1004 1 0
100 4 1 4
10 0 -> 5 10 54
1 0 -> 5 100 554
0 1 1000 1554
1
Borel On

Is there a reason you are using modulus to replace?

    public class Replaceall0swith5 {
        public static void convertFive(int n) {
            int replacedValues = Integer.valueOf(String.valueOf(n).replace("0","5"));
            System.out.print(n + " All O's replaced with 5 " + replacedValues);
    
        }
    
        public static void main(String[] args) {
            Replaceall0swith5.convertFive(1004);
        }
    }
0
sittsering On

This is basically the same as reversing a number except it changes 0 to 5.

while (n > 0) {
        digit = n % 10;
        if (digit == 0) {
            digit = 5;
        }
        sum = sum * 10 + digit;
        n = n / 10;
    }

convertFive(1004) gives 4551 instead of 1554.
digit = 4 : sum = 0 * 10 + 4 = 4
digit = 0 : sum = 4 * 10 + 5 = 45
digit = 0 : sum = 45 * 10 + 5 = 455
digit = 1 : sum = 455 * 10 + 1 = 4551
Easy solution would be converting it to string and replace 0 by 5. @Fmxerz already gave the solution for that.
or if you are going with this, you can use Math.pow function.

import java.lang.Math;
....

public static void convertFive(int n) {
    int i = 0;
    int digit, sum = 0;
    while (n > 0) {
        digit = n % 10;
        if (digit == 0) {
            digit = 5;
        }
        sum = sum + digit*(int)Math.pow(10,i);
        n = n / 10;
        i++;
    }
    System.out.print(n + " All O's replaced with 5 " + sum);
}