(SPOJ) 2281 - Rumo aos 9s - Solução

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

class Main {
    public static void main(String[] args) throws NumberFormatException, IOException {
        Main processando = new Main();
        processando.processa();
       
        System.exit(0);
    }
   
    void processa() throws NumberFormatException, IOException {
        String line = "";
       
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        while((line = br.readLine()) != null) {
            if (line.charAt(0) == '0' && line.length() == 1) {
                return;
            }
           
            String leituraTmp = line;
           
            int soma = 0;
            int contador = 0;
            boolean multiplo = false;
            boolean finaliza = false;
            while (!finaliza) {
                soma = 0;
                for (int i = 0; i < line.length(); i++) {
                    soma += line.charAt(i)-'0';           
                }
                contador++;

                line = Integer.toString(soma);
               
                if (contador == 1 && soma%9 == 0) {
                    multiplo = true;
                }
                if ((contador == 1 && soma%9 != 0) || line.length() == 1) {
                    finaliza = true;
                }
            }
           
            if (multiplo) {
                bw.write(leituraTmp + " is a multiple of 9 and has 9-degree " + contador + ".\n");
            }
            else {
                bw.write(leituraTmp + " is not a multiple of 9.\n");
            }           
           
            bw.flush();
        }
       
        bw.close();
        
        return;
    }
}

Comments

Popular posts from this blog

(Coderbyte) Powers of Two - Solução

(Coderbyte) Dash Insert II - Solução

(CoderByte) Number Search - Solução