Find Greatest Number by Rearranging Same Digits

package org.wesome.dsalgo;

class LargestNumber {
    public static int largestNumber(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 largestNumber = new StringBuilder();
        for (int i = 9; i >= 0; i--) {
            for (int j = 0; j < frequency[i]; j++) {
                largestNumber.append(i);
            }
        }
        return Integer.parseInt(largestNumber.toString());
    }
}
package org.wesome.dsalgo;

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

import static org.wesome.dsalgo.LargestNumber.largestNumber;

public class LargestNumberTest {
    @Test
    void largestNumberTest1() {
        int number = 212;
        Assertions.assertEquals(221, largestNumber(number));
    }

    @Test
    void largestNumberTest2() {
        int number = 111;
        Assertions.assertEquals(111, largestNumber(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