Jun 27

C程序实现数字反转 不指定

Heck , 23:26 , 编程杂谈 , 评论(0) , 引用(0) , 阅读(1862) , Via 本站原创 | |
         有个朋友问我用C怎么实现两个数字反转,也就是逆序,想了下我也有很久没用过C了,其实也简单,和10相乘再加上该数与10取余的和,给出以下实现:
Iterative Way
Algorithm:
Input:  num
(1) Initialize rev_num = 0
(2) Loop while num > 0
     (a) Multiply rev_num by 10 and add remainder of num
          divide by 10 to rev_num
               rev_num = rev_num*10 + num%10;
     (b) Divide num by 10
(3) Return rev_num

Example:
num = 4562
rev_num = 0
rev_num = rev_num *10 + num%10 = 2
num = num/10 = 456
rev_num = rev_num *10 + num%10 = 20 + 6 = 26
num = num/10 = 45
rev_num = rev_num *10 + num%10 = 260 + 5 = 265
num = num/10 = 4
rev_num = rev_num *10 + num%10 = 265 + 4 = 2654
num = num/10 = 0


Program:
#include  
/* Iterative function to reverse digits of num*/
int reversDigits(int num)
{
    int rev_num = 0;
    while(num > 0)
    {
        rev_num = rev_num*10 + num%10;
        num = num/10;
    }
    return rev_num;
}

/*Driver program to test reversDigits*/
int main()
{
    int num = 4562;
    printf("Reverse of no. is %d", reversDigits(num));
  
    getchar();
    return 0;
}
Time Complexity: O(Log(n)) where n is the input number.
RECURSIVE WAY
#include  
/* Recursive function to reverse digits of num*/
int reversDigits(int num)
{
  static int rev_num = 0;
  static int base_pos = 1;
  if(num > 0)
  {
    reversDigits(num/10);
    rev_num  += (num%10)*base_pos;
    base_pos *= 10;
  }
  return rev_num;
}
  
/*Driver program to test reversDigits*/
int main()
{
    int num = 4562;
    printf("Reverse of no. is %d", reversDigits(num));
  
    getchar();
    return 0;
}
Time Complexity: O(Log(n)) where n is the input number
Note that above above program doesn’t consider leading zeroes. For example, for 100 program will print 1. Try extensions of above functions that should also work for floating point numbers.


来源:Heck's Blog
地址:http://www.hecks.tk/reverse-digits-of-num-with-c/
转载时须以链接形式注明作者和原始出处及本声明,否则将追究法律责任,谢谢配合!