The algorithm counts the number of decimal digits [loop], and outputs each digit of the number in positive and reverse order

Count the number of decimal digits in
order, output each digit of the number in reverse order, output each digit of the number in
reverse order

(1) Count the number of decimal digits [loop]


Count how many digits is an integer? Integers can be negative, zero or positive.*

Example 1:

Input: 0

Output: 1

Example 2:

Input: 123456789

Output: 9

Example 3:

Input: -123456789

Output: 9

Algorithm: discard single digits each time until 0, count the number of discards

int NumofIntBit(int n)
{
    
    
	int ans = 0;
	if (n == 0)
	{
    
    
		ans = 1;
	}
	while (n != 0)
	{
    
    
		n = n / 10;
		ans++;
	}
	return ans;
}

(2) Output each digit of the number sequentially [loop, recursion]

Given an integer, output each digit of the number, for example, the output result of 123456 is 1 2 3 4 5 6.

Example 1:

Input: 123456

Output: 1 2 3 4 5 6

Algorithm 1: Use the loop to get the highest digit, output it, and then discard it until it is 0.

void PrintOrder(int n)  

{
    
      

    if(n == 0)  

    {
    
      

        printf("0\n");  

        return ;  

    }  
    int m = n;  

    int count = 0;//统计n的位数  

    while(m != 0)  

    {
    
      

        m /= 10;//丢弃个位  

        count++;  

    }  

    int power = (int)pow(10.0,count-1);//需要引用math.h  
   while(n != 0)  

    {
    
      

        printf("%d ",n/power);//输出最高位  

        n %= power; //丢弃最高位  

        power /= 10;  

    }  

} 

Algorithm 2: Use recursive output data

void OutPositiveSequence(int n)
{
    
    
	if (n < 10)
		printf("%d\n", n);
	else
	{
    
    
		OutPositiveSequence(n / 10);
		printf("%d\n", n % 10);
	}
}

(3) Output each digit of the number in reverse order [loop]


Given an integer, output each digit of the number in reverse order, for example, the output result of 123456 is 6 5 4 3 2 1

Example 1:

Input: 123456

Output: 6 5 4 3 2 1

Algorithm 1: Get the ones digit, output the ones digit, and then discard the ones digit until 0

void PrintReverse(int n)  

{
    
      

    do  

    {
    
      

        printf("%d ",n%10);//得到并输出个位  

        n /= 10;//丢弃个位  

    }while(n != 0);  

    printf("\n"); 
} 

Guess you like

Origin blog.csdn.net/Gunanhuai/article/details/109262641