Trong bài viết này, chúng ta sẽ tìm hiểu cách đếm số chữ số trong một số nguyên. Việc đếm được thực hiện bằng vòng lặp và một biến đếm.
Dưới đây là minh họa:
Đầu vào
Giả sử đầu vào là:
Số: 15161718
Đầu ra
Kết quả mong đợi:
Kết quả là: 8
Thuật toán
Bước 1 - BẮT ĐẦU Bước 2 – Khai báo hai giá trị nguyên: my_count và my_input Bước 3 - Đọc giá trị từ người dùng hoặc định nghĩa trước Bước 4 – Sử dụng vòng lặp for, chia giá trị đầu vào cho 10 cho đến khi số giảm xuống giá trị thấp nhất. Tăng biến đếm mỗi lần. Bước 5 - Hiển thị giá trị biến đếm Bước 6 - DỪNG
Ví dụ 1: Nhập từ bàn phím
Người dùng nhập giá trị dựa trên lời nhắc. Thử trực tiếp trong coding ground.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int my_count, my_input;
my_count = 0;
System.out.println("Required packages have been imported");
Scanner my_scanner = new Scanner(System.in);
System.out.println("A reader object has been defined");
System.out.print("Enter the number: ");
my_input = my_scanner.nextInt();
for (; my_input != 0; my_input /= 10, ++my_count) {
}
System.out.println("The number of digits in the given input is: " + my_count);
}
}
Đầu ra
Required packages have been imported A reader object has been defined Enter the number: 15161718 The number of digits in the given input is: 8
Ví dụ 2: Giá trị định nghĩa trước
Số nguyên đã được định nghĩa trước, giá trị được truy xuất và hiển thị.
public class Main {
public static void main(String[] args) {
int my_count = 0, my_input;
my_count = 0;
my_input = 15161718;
System.out.println("The number is defined as " + my_input);
for (; my_input != 0; my_input /= 10, ++my_count) {
}
System.out.println("The number of digits in the given input is: " + my_count);
}
}
Đầu ra
The number is defined as 15161718 The number of digits in the given input is: 8