Search code examples
javaalgorithmdata-structuresfundamentals-ts

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


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

Solution

  • 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