Created
September 10, 2011 12:02
-
-
Save nartamonov/1208230 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Main { | |
public static void main(String[] args) { | |
// Генерируем случайное число в интервале (0, 10000) | |
int num = (new java.util.Random()).nextInt(10001); | |
System.out.printf("Сгенерировали число: %d\n", num); | |
// Выводим количество цифр в сгенерированном числе | |
System.out.printf("Количество цифр в этом числе: %d\n", countDigits(num)); | |
// Выводим первую цифру слева | |
System.out.printf("Первая цифра слева: %d\n", leftDigit(num)); | |
// Выводим сумму цифр в числе | |
System.out.printf("Сумма цифр в числе: %d\n", digitSum(num)); | |
// Выводим зеркально отраженное число | |
System.out.printf("Число с обратным порядком цифр: %d\n", mirrorNum(num)); | |
} | |
// Возвращает количество цифр в числе `num`. | |
public static int countDigits(int num) { | |
int digits = 1; | |
while (num / 10 != 0) { | |
digits += 1; | |
num = num / 10; | |
} | |
return digits; | |
} | |
// Возвращает первую цифру слева числа `num`. | |
public static int leftDigit(int num) { | |
do { | |
num = num / 10; | |
} while (num / 10 != 0); | |
return num; | |
} | |
// Возвращает сумму цифр в числе `num`. | |
public static int digitSum(int num) { | |
int sum = 0; | |
while (num != 0) { | |
sum += num % 10; | |
num = num / 10; | |
} | |
return sum; | |
} | |
// Возвращает число с переставленными обратном порядке цифрами числа `num`. | |
public static int mirrorNum(int num) { | |
int mirror = 0; | |
while (num != 0) { | |
mirror = mirror * 10 + (num % 10); | |
num = num / 10; | |
} | |
return mirror; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment