C++ 程序来检查给定数是幸运数还是不是(所有数字都不相同)
给定一个数,任务是检查输入的数是幸运数还是不是,并将结果显示出来。
什么是幸运数
幸运数是每个数字都不同的数,如果至少有一个数字重复,那么该数将不被视为幸运数。
示例
Input-: n = 1234 Output-: it is a lucky number Explanation-: As there is no repeating digit in a number n so it is a lucky number Input-: n = 3434 Output-: it is not a lucky number Explanation-: In the given number n, 3 and 4 are repeating twice so it is not a lucky number
我们对给定程序所采取的方法如下 −
- 从用户处输入数字 n,以检查它是否是幸运数
- 遍历所有数字,直到数字大小
- 标记访问过的数字,并在每次访问时检查它是否已经发现
- 显示给定的数字是幸运数还是不是
算法
Start Step1-> declare function to check whether a given number is lucky or not bool check_lucky(int size) declare bool arr[10] Loop For int i=0 and i<10 and i++ Set arr[i] = false End Loop While(size > 0) declare int digit = size % 10 IF (arr[digit]) return false End set arr[digit] = true Set size = size/10 End return true Step 2-> In main() Declare int arr[] = {0,34,2345,1249,1232} calculate int size = sizeof(arr)/sizeof(arr[0]) Loop For int i=0 and i<size and i++ check_lucky(arr[i])? print is Lucky : print is not Lucky End Stop
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
示例
#include<iostream> using namespace std; //return true if a number if lucky. bool check_lucky(int size) { bool arr[10]; for (int i=0; i<10; i++) arr[i] = false; while (size > 0) { int digit = size % 10; if (arr[digit]) return false; arr[digit] = true; size = size/10; } return true; } int main() { int arr[] = {0,34,2345,1249,1232}; int size = sizeof(arr)/sizeof(arr[0]); for (int i=0; i<size; i++) check_lucky(arr[i])? cout << arr[i] << " is Lucky \n": cout << arr[i] << " is not Lucky \n"; return 0; }
输出
19 is Lucky 34 is Lucky 2345 is Lucky 1249 is Lucky 1232 is not Lucky
广告