Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class lab22 {
- public static int inputNumber() {
- Scanner scanner = new Scanner(System.in);
- final int MAX_NUMBER = 100000000;
- boolean isIncorrect;
- int number;
- number = 0;
- System.out.printf("Введите натуральное число не большее, чем %,d \n", MAX_NUMBER);
- do {
- isIncorrect = false;
- try {
- number = Integer.parseInt(scanner.nextLine());
- } catch (Exception ex) {
- System.out.printf("Нужно ввести натуральное число, не большее, чем %,d \n", MAX_NUMBER);
- isIncorrect = true;
- }
- if (!isIncorrect && (number < 1 || number > MAX_NUMBER)) {
- System.out.printf("Число должно быть больше 0 и не больше чем %,d \n", MAX_NUMBER);
- isIncorrect = true;
- }
- } while (isIncorrect);
- scanner.close();
- return number;
- }
- public static int searchMaxCountOfRepeats(int number) {
- int maxCountOfRepeats, counter, previous, singleNumber, newNumber;
- maxCountOfRepeats = 0;
- while (number > 0) {
- counter = 1;
- singleNumber = number % 10;
- previous = singleNumber;
- number = number / 10;
- newNumber = number;
- while (newNumber > 0)
- {
- singleNumber = newNumber % 10;
- newNumber = newNumber / 10;
- if (previous == singleNumber)
- counter++;
- if (counter > maxCountOfRepeats)
- maxCountOfRepeats = counter;
- }
- }
- return maxCountOfRepeats;
- }
- public static void allSolutions(int number, int maxCountOfRepeats) {
- int counter, previous, singleNumber, newNumber;
- while (number > 0) {
- counter = 1;
- singleNumber = number % 10;
- previous = singleNumber;
- number = number / 10;
- newNumber = number;
- while (newNumber > 0) {
- singleNumber = newNumber % 10;
- newNumber = newNumber / 10;
- if (previous == singleNumber) {
- counter++;
- if (counter == maxCountOfRepeats)
- System.out.print(previous + " ");
- }
- }
- }
- }
- public static void printResult(int number, int maxCountOfRepeats) {
- System.out.println("Самая часто встречающаяся цифра/цифры: ");
- if (maxCountOfRepeats == 1)
- System.out.println("Такой цифры нет.");
- if (maxCountOfRepeats == 0)
- System.out.println(number);
- else
- allSolutions(number, maxCountOfRepeats);
- }
- public static void main(String[] args) {
- int maxCountOfRepeats, number;
- System.out.println("Программа позволяет узнать, какая цифра в данном числе встречается чаще всего.");
- number = inputNumber();
- maxCountOfRepeats = searchMaxCountOfRepeats(number);
- printResult(number, maxCountOfRepeats);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement