Introduction

This is my blog of programming, I take notes and leave codes of computer science problems I solved here. Be my guest to comment :)

Friday, March 8, 2013

uva 10018 - Reverse and Add

/*
 Problem link
 Type: Ad hoc
 Algorithm:
 */

import java.io.*;
import java.util.*;

public class uva10018 {
   
static long n;
   
@SuppressWarnings("resource")
public static void main(String args[]) {
    /*InputStream inputStream;
      try {
       inputStream = new FileInputStream("10018.inp");
      } catch (
              IOException e) {
       throw new RuntimeException(e);
      }
      OutputStream outputStream;
      try {
       outputStream = new FileOutputStream("10018.out");
      } catch (IOException e) {
       throw new RuntimeException(e);
      }*/
    Scanner in = new Scanner(System.in);
    PrintWriter out = new PrintWriter(System.out);
    int nTest = in.nextInt();
    for (int test=1; test<=nTest; test++)
    {
        n = in.nextInt();
        out.println(Solve() + " " +n);
    }
    in.close();
    out.close();
}

static long Solve() {
    long tmp,palind,cnt = 0, x = n;
    String so;
    boolean ok;
    while (true) {
        so = "";
        tmp = x;
        palind = 0;
        ok = true;
        cnt++;
        while (tmp>0) {
            palind = palind*10 + tmp%10;
            tmp /= 10;
        }
        palind += x;
        x = palind;
        while (palind>0) {
            so = so + (char)(palind%10+48);
            palind /= 10;
        }
        for (int i=0; i<so.length()/2; i++)
            if (so.charAt(i)!=so.charAt(so.length()-i-1)) {
                ok = false;
                break;
            }
        if (ok)
        {
            n = x;
            return(cnt);
        }
    }
}

}

No comments:

Post a Comment