Tuesday, 18 October 2022

Find the smallest digit and its positions in a given number

Problem statement

Given a number as input, you need to find the smallest digit in the given number and its positions.

 

Following program takes an integer as input, traverse to each digit of the number, and get the smallest digit and its positions (positions are from 0 indexed).

 

Find the below working application.

 

SmallestDigitDemo.java

package com.sample.app;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class SmallestDigitDemo {

	static class MinValueAndPosition {
		int number;
		List<Integer> positions;
	}

	public static void main(String[] args) {
		try (Scanner scanner = new Scanner(System.in)) {
			System.out.println("Enter an integer : ");
			int number = scanner.nextInt();

			if (number < 0) {
				number = number * -1;
			}
			final String str = Integer.toString(number);
			final MinValueAndPosition minValueAndPosition = getMinimumDigigPositions(str);
			System.out.println("Minimum value : " + minValueAndPosition.number);
			System.out.println("position - " + minValueAndPosition.positions);
		}

	}

	static MinValueAndPosition getMinimumDigigPositions(final String num) {
		final List<Integer> list = new ArrayList<>();
		int minVal = Integer.MAX_VALUE;
		int counter = -1;
		for (char ch : num.toCharArray()) {
			counter++;
			int val = Integer.parseInt(ch + "");

			if (val < minVal) {
				minVal = val;
				list.clear();
				list.add(counter);
				continue;
			}

			if (val == minVal) {
				list.add(counter);
			}

		}

		MinValueAndPosition minValueAndPosition = new MinValueAndPosition();
		minValueAndPosition.number = minVal;
		minValueAndPosition.positions = list;
		return minValueAndPosition;

	}
}

Output

Enter an integer : 
1234512341
Minimum value : 1
position - [0, 5, 9]


You may like

 

No comments:

Post a Comment