Yêu cầu
– Nhập vào số nguyên dương n (n > 0) từ cửa sổ màn hình console.
– Tìm chữ số đầu tiên của số nguyên dương
Giải thuật
– Dùng vòng lặp do while() để bắt người dùng nhập lại giá trị n nếu nhập giá trị n <= 0
– Dùng phép toán n%10 và n/10 để tách các chữ số của số nguyên.
Code
package net.vncoding; import java.util.Scanner; public class JavaCore { public static void main(String[] args) { int n; int res; Scanner sc; do { System.out.print("Input n = "); sc = new Scanner(System.in); n = sc.nextInt(); }while(n <= 0); res = first_digit_of_num(n); System.out.println("First digit of " + n + " is " + res); sc.close(); } public static int first_digit_of_num(int n) { int first_digit = 0; while(n > 0) { first_digit = n%10; n = n/10; } return first_digit; } }
Kết quả
Leave a Reply
You must be logged in to post a comment.