table of Contents
(1) Find the number of digits of a positive integer
(2) Find the number on each digit of an integer
1. Problem description
problem:
Give a positive integer with no more than 5 digits, and require:
① Find out how many digits it is;
② Output each digit separately;
③Output each digit in reverse order
Examples:
123 is a 3-digit number, the hundreds, tens, and ones digits are 1, 2 and 3 respectively; the output in reverse order is 321;
enter:
123
Output:
3
1 2 3
321
2. Problem solving
problem analysis:
(1) Find the number of digits of a positive integer
Method 1: Divide a positive integer by 10, each time the integer can be divided by one, and the count is increased by one, until the integer is 0;
For example: 123/10=12 count count=1; 12/10=1 count count=2; 1/10=0 count count=3, the quotient is 0, the end, the integer 123 is a 3-digit number.
programming:
//求正整数的位数
int figure(int num) {
int count = 0;
if (num == 0) {
count = 1;
}
else {
while (num) {
num /= 10;
count++;
}
}
return count;
}
Method 2: Use the function log10(x)+1
log() function introduction:
Header file : <math.h>
Function prototype : double log(double x);
Function : Find the logarithm based on natural numbers
Parameters : double x is a true number and must be greater than 0
Return value : Returns the logarithm based on the natural number
Formula : loge x = b
Note : The natural number e is a constant 2.71828
When the base is changed to 10, the number of digits can be solved. We know that log10(10)=1, the closed interval [1-9] is a 1-digit integer; log10(100)=2, the closed interval [10-99] is a 2-digit integer, so the number of integers to be solved is log10( x)+1 ;
int figure2(int num) {
if (num == 0) {
return 1;
}
else {
return ((int)log10(num)) + 1;//由于log函数返回类型是double,所以使用(int)进行强制转换
}
}
(2) Find the number on each digit of an integer
The remainder of an integer is 10 (%10) to get the number on the last digit of the integer, for example: 123%10=3 ;
Dividing an integer by 10 (/10) can eliminate the last digit of the integer, for example: 123/10=12 (because of an integer/integer, the result is still an integer, which is equivalent to rounding the result)
//求整数各位的数字
/*
返回类型为:整型数组指针(返回的是存放各位数字的数组起始地址)
num为待处理数字,数组a为存储数组
*/
int* figure_num(int num,int a[5]) {
int i = 0;
while(num){
a[i] = num % 10;
num /= 10;
i++;
}
return a;
}
int main() {
int num = 123;
int len = figure2(num);//计算整数位数
int arr[5];
int* p = arr;
p = figure_num(num,arr);//返回存储地址
for (int i = len-1; i >=0; i--) {
printf("%d ", arr[i]);//由高位向低位依次输出
}
}
(3) Reverse order output
It's relatively simple. When directly looping output, press 0~len-1 to output in turn.
Infer other things: What if you want to output the reversed integer of an integer?
//逆序数
int reverse_num(int num) {
int res = 0;
while (num) {
res = res * 10 + num % 10;
num /= 10;
}
return res;
}