Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Joana M. F. da Trindade http://www.inf.ufrgs.br/~jmftrindade

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

A solution for the "Reverse and Add" problem

A solution for the "Reverse and Add" problem.

Problem description:
http://icpcres.ecs.baylor.edu/onlinejudge/external/100/10018.html

Author: Joana Matos Fonseca da Trindade
Date: 2008.04.14

   1  
   2  /*
   3   * Solution for the "Reverse and Add" problem.
   4   * UVa ID: 10018
   5   */
   6  #include <iostream>
   7  
   8  #define NDIGITS 100
   9  
  10  using namespace std;
  11  
  12  /* returns the reversed number */
  13  unsigned long long reverse(unsigned long long number) {
  14  	unsigned long long m = 0; /* reversed number */
  15  	int digits[NDIGITS]; /* digits array */
  16  	int pos = 0, power = 1;
  17  	
  18  	/* init */
  19  	for (int i=0; i<NDIGITS; i++) {
  20  		digits[i] = 0;
  21  	}
  22  	
  23  	/* retrieve all digits */
  24  	while (number > 0) {
  25  		digits[pos++] = number % 10;
  26  		number = number / 10;
  27  	}
  28  
  29  	/* multiply the reversed digits by the powers of ten */
  30  	for (int i=pos-1; i>=0; i--) {
  31  		m += power * digits[i];
  32  		power *= 10;
  33  	}
  34  	
  35  	return m;
  36  }
  37  
  38  /* main */
  39  int main() {
  40  	int nc; /* number of cases */
  41  	int m; /* minimum number of iterations */
  42  	unsigned long long n; /* number */
  43  	
  44  	cin >> nc;
  45  	
  46  	/* reverse and add.. */
  47  	for (int i=0; i<nc; i++) {
  48  		cin >> n;
  49  		m = 0;
  50  		while (true) {
  51  			if (reverse(n) == n) {
  52  				break;
  53  			} else {
  54  				n += reverse(n);
  55  				m++;
  56  			}
  57  		}
  58  		cout << m << " " << n << endl;
  59  	}
  60  	
  61  	return 0;
  62  } 
  63  
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS