write a program in java to print the digit of a number in ascending order or descending order
Answers
Answered by
7
◆Hey There◆
Java For Ascending Order
public static void sortDigits(int x) {
Map<Integer, Integer> digitCounts = new HashMap<>();
while (x > 0) {
int digit = x % 10;
Integer currentCount = digitCounts.get(digit);
if (currentCount == null) { currentCount = 0; } digitCounts.put(x % 10, currentCount + 1);
x = x / 10;
} for (int i = 0; i < 10; i++) { Integer count = digitCounts.get(i); if (count == null) { continue; } for (int j = 0; j < digitCounts.get(i); j++) { System.out.print(i); } } }
Java For Ascending Order
public static void sortDigits(int x) {
Map<Integer, Integer> digitCounts = new HashMap<>();
while (x > 0) {
int digit = x % 10;
Integer currentCount = digitCounts.get(digit);
if (currentCount == null) { currentCount = 0; } digitCounts.put(x % 10, currentCount + 1);
x = x / 10;
} for (int i = 0; i < 10; i++) { Integer count = digitCounts.get(i); if (count == null) { continue; } for (int j = 0; j < digitCounts.get(i); j++) { System.out.print(i); } } }
Answered by
6
public
class
Sort Digits
{
public
static
void main
(String[] args)
{
sortDigits(3413657);
}
public
static
void
sortDigits. (int num)
{
System.out.println("Number : " + num);
String number = Integer.toString(num); int len = number.length(); /
/ get length of the number int[] digits = new int[len]; int i = 0; while (num != 0)
{
int digit = num % 10; digits[i++] = digit; // get all the digits num = num / 10
; }
System.out.println("Digit before sorting: ");
for (int j : digits)
{
System.out.print(j + ","); } sort(digits);
System.
out.
println("\nDigit After sorting: ");
for (int j : digits)
{
System.out.print(j + ","); } } //simple bubble sort public static void sort(int[] arr) { for (int i = 0;
i < arr.length - 1; i++) for (int j = i + 1; j < arr.length; j++)
{
if (arr[i] > arr[j]) { int tmp = arr[j]; arr[j] = arr[i]; arr[i] = tmp;
}
}
}
}
Similar questions