Find Smallest Number by Rearranging Same Digits

package org.wesome.dsalgo;

class SmallestNumber {
    public static int smallestNumber(int number) {
        int[] frequency = new int[10];
        while (number != 0) {
            if (number == 0) {
                break;
            }
            /*  % or module operator will give the reminder */
            int val = number % 10;
            frequency[val]++;
            number = number / 10;
        }
        StringBuilder smallestNumber = new StringBuilder();
        for (int i = 1; i <=9; i++) {
            for (int j = 0; j < frequency[i]; j++) {
                smallestNumber.append(i);
            }
        }
        return Integer.parseInt(smallestNumber.toString());
    }
}
package org.wesome.dsalgo;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import static org.wesome.dsalgo.SmallestNumber.smallestNumber;

public class SmallestNumberTest {
    @Test
    void smallestNumberTest1() {
        int number = 212;
        Assertions.assertEquals(122, smallestNumber(number));
    }

    @Test
    void smallestNumberTest2() {
        int number = 987654321;
        Assertions.assertEquals(123456789, smallestNumber(number));
    }
}
plugins {
    id 'java'
    id "io.freefair.lombok" version "6.2.0"
}

group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}

test {
    useJUnitPlatform()
}

 

follow us on