Created
June 10, 2012 01:54
-
-
Save sanrodari/2903502 to your computer and use it in GitHub Desktop.
SumarArreglos.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.trabajo; | |
import java.util.Arrays; | |
import javax.swing.JOptionPane; | |
public class SumaEnArrays { | |
public static void main(String[] args) { | |
String operando1 = JOptionPane.showInputDialog("Primer operando"); | |
String operando2 = JOptionPane.showInputDialog("Segundo operando"); | |
int[] arreglo1 = convertirCadenaArreglo(operando1); | |
int[] arreglo2 = convertirCadenaArreglo(operando2); | |
int mayor = arreglo1.length > arreglo2.length ? arreglo1.length : arreglo2.length; | |
int[] resultado = new int[mayor + 1]; | |
boolean iguales = arreglo1.length == arreglo2.length; | |
int loQuellevo = 0; | |
for (int i = 0; i < mayor; i++) { | |
// Cuando los arreglos tiene el mismo tamaño. | |
if(iguales) { | |
int suma = arreglo1[i] + arreglo2[i] + loQuellevo; | |
if(suma == 2){ | |
loQuellevo = 1; | |
resultado[i] = 0; | |
} | |
else if(suma == 3){ | |
loQuellevo = 1; | |
resultado[i] = 1; | |
} | |
else{ | |
loQuellevo = 0; | |
resultado[i] = suma; | |
} | |
if(i == mayor - 1){ | |
resultado[i + 1] = loQuellevo; | |
} | |
} | |
// Cuando los arreglos NO tienen el mismo tamaño. | |
else { | |
int[] pequeno = arreglo1.length < arreglo2.length ? arreglo1 : arreglo2; | |
int[] grande = arreglo1.length > arreglo2.length ? arreglo1 : arreglo2; | |
int operandoPequeno = 0; | |
// Cuando se puede acceder al indice del arreglo pequeño | |
if(i < pequeno.length){ | |
operandoPequeno = pequeno[i]; | |
} | |
// Cuando NO se puede acceder al indice del arreglo pequeño | |
else{ | |
operandoPequeno = 0; | |
} | |
int suma = operandoPequeno + grande[i] + loQuellevo; | |
if(suma == 2){ | |
loQuellevo = 1; | |
resultado[i] = 0; | |
} | |
else if(suma == 3){ | |
loQuellevo = 1; | |
resultado[i] = 1; | |
} | |
else{ | |
loQuellevo = 0; | |
resultado[i] = suma; | |
} | |
if(i == mayor - 1){ | |
resultado[i + 1] = loQuellevo; | |
} | |
} | |
} | |
int[] reversado = new int[resultado.length]; | |
for (int i = 0; i < resultado.length; i++) { | |
reversado[i] = resultado[resultado.length - 1 - i]; | |
} | |
System.out.println(Arrays.toString(reversado)); | |
} | |
public static int[] convertirCadenaArreglo(String operando){ | |
int[] arrreglo = new int[operando.length()]; | |
for (int i = 0; i < arrreglo.length; i++) { | |
arrreglo[i] = Integer.parseInt("" + operando.charAt(arrreglo.length - 1 - i)); | |
} | |
return arrreglo; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment