Mô tả bài toán
Tạo ứng dụng Console, cho người dùng nhập vào con số
num. In ra con số đảo ngược của số người dùng vừa nhập.
Ví dụ: người dùng nhập
num=1234, chương trình in ra kết quả:
4321
Cách giải quyết 1
Tạo con số đảo ngược bắt đầu từ 0:
reverve=0
Sử dụng vòng lặp
while để duyệt con số:
- Cứ mỗi lần duyệt 1 con số tương đương với tăng 1 ký tự số:
reverse = reverse * 10
- Lấy số reverse hiện tại cộng với số chia lấy dư của num cho 10:
reverse = reverse + (num%10)
- Loại bỏ ký tự hàng đơn vị vừa duyệt:
num = num / 10
Source code
1/*
2C# Program to Get a Number and Display the Number with its Reverse
3This is a C# Program to get a number and display the number with its reverse.
4
5Problem Description
6This C# Program Gets a Number and Display the Number with its Reverse.
7
8Problem Solution
9Here we obtain a number from the user and display the digits in the reverse order.
10*/
11using System;
12using System.Collections.Generic;
13using System.Linq;
14using System.Text;
15
16namespace Lession4
17{
18 class Program
19 {
20 static void Main(string[] args)
21 {
22 int num, reverse = 0;
23 Console.WriteLine("Enter a Number : ");
24 num = int.Parse(Console.ReadLine());
25 while (num != 0)
26 {
27 reverse = reverse * 10;
28 reverse = reverse + num % 10;
29 num = num / 10;
30 }
31 Console.WriteLine("Reverse of Entered Number is : " + reverse);
32 Console.ReadLine();
33
34 }
35 }
36}
Cách giải quyết 2 (tự làm nhé)
Lưu con số người dùng nhập thành 1 chuỗi các ký tự. Sau đó sử dụng vòng lặp duyệt ngược từ phần tử cuối cùng -> phần tử đầu tiên, mỗi lần duyệt, in ký tự ra người dùng.
Github
https://github.com/kellyfire611/learning.nentang.vn-csharp/tree/master/src/Lession4