I want to read a number from the user and then sum the last seven digits of the entered number. What is the best way to do this? This is my code, but unfortunately it does not work:
class ersteAufgabe {
public static void main (String[] args)
{
Scanner s = new Scanner(System.in);
double [] a = new double[10];
for (int i = 0;i<10;i++)
{
a[i]=s.nextInt();
}
s.close();
System.out.println(a[0]);
}
}
I wanted only one number to be read and used as an array. Only now he expects 10 inputs from me.
public static int lastDigitsSum(int total) {
try (Scanner scan = new Scanner(System.in)) {
String str = scan.next();
int count = 0;
for (int i = str.length() - 1, j = 0; i >= 0 && j < total; i--, j++) {
if (Character.isDigit(str.charAt(i)))
count += str.charAt(i) - '0';
else
throw new RuntimeException("Input is not a number: " + str);
}
return count;
}
}
First you have to recognize if the entered value is a number and has at least 7 digits. Unless you have to output an error message. Convert the entered value to String and use the class Character.isDigit(); to check if the characters are numbers. Then you can use some methods from the String class like substring(..). At the end do a Unit-Test with erroneous/valid values to see if your code is robust. Close the BufferedReader and Resources when you are done by using finally { br.close() }. Push your code in methods and use an instance class erste-Aufgabe (first exercise).. When you are really really done use JFrame for a GUI-Application.
private static final int SUM_LAST_DIGITS = 7;
public void minimalSolution() {
String enteredValue = "";
showInfoMessage("Please enter your number with at least " + SUM_LAST_DIGITS + " digits!");
try (Scanner scan = new Scanner(System.in)) {
enteredValue = scan.next();
if (enteredValue.matches("^[0-9]{" + SUM_LAST_DIGITS + ",}$")) {
showInfoMessage(enteredValue, lastDigitsSum(enteredValue));
} else {
showErrorMessage(enteredValue);
}
} catch(Exception e) {
showErrorMessage(e.toString());
}
}
public int lastDigitsSum(String value) {
int count = 0;
for (int i = value.length() - 1, j = 0; i >= 0 && j < SUM_LAST_DIGITS; i--, j++)
count += value.charAt(i) - '0';
return count;
}
public void showInfoMessage(String parMessage) {
System.out.println(parMessage);
}
public void showInfoMessage(String parValue, int parSum) {
System.out.println("Your entered value: [" + parValue + "]");
System.out.println("The summed value of the last 7 digits are: [" + parSum + "]");
}
public void showErrorMessage(String parValue) {
System.err.println("Your entered value: [" + parValue + "] is not a valid number!");
}
i seem to be having trouble figuring out what to set the variable intValue to under the read value methods. The program is supposed to take 10 integers and average them, it works fine as far as catching exceptions and input, but the output displays all the numbers as 0 (because i set it to 0 temporarily but can not figure out what to change it to). Heres the code
package averagenumdriver;
import static java.lang.Integer.parseInt;
import java.util.Scanner;
public class AverageOfIntegers {
//Declare variables
private int numberOfValues;
private int[] integerValues;
private double average;
public AverageOfIntegers(int numberOfValues){
this.numberOfValues = numberOfValues;
}
//Define the readValues()
public void readValues(){
String stringValue = null;
int intValue = 0, i;
Scanner console = null;
i = 0;
integerValues = new int[numberOfValues];
while(i < numberOfValues){
try
{
console = new Scanner(System.in);
System.out.print("Enter value : ");
//read the value
stringValue = console.nextLine();
//check for number
intValue = 0;
parseInt(stringValue);
//Store only integer values
integerValues[i++] = intValue;
}
catch(NumberFormatException ex)
{
//Catch exception and handle it
System.out.println("Invalid Number entered" + "Reenter again ");
continue;
}
}
}
//read integer values
public void printValues()
{
System.out.println("Given values are ");
for (int i = 0; i < numberOfValues; i++)
{
System.out.println("Number: " + (i + 1) + " = " +
integerValues[i]);
}
}
public double getAverage()
{
int sum = 0;
//Calcualte the sum of integer values
for (int i = 0; i < numberOfValues; i++)
{
sum += integerValues[i];
}
//calculate average
average = (double)sum / numberOfValues;
return(average);
}
}
EDIT* question seems to be marked as a duplicate, but I am not asking about why division with two integers where the denominator is greater than numerator yields a 0.
Change
//check for number
intValue = 0;
parseInt(stringValue);
TO
//check for number
intValue = parseInt(stringValue);
I am trying to run a program that outputs the sum of every digit of an entered in integer. How would I go about reading the number and outputting each digit?
Example: Input is 4053 the output would be "4+0+5+3 = 12".
import java.util.Scanner;
public class Digits{
public static void main(String args[]) {
//Scans in integer
Scanner stdin = new Scanner(System.in);
System.out.println("Enter in a number: ");
int number = stdin.nextInt();
//Set sum to zero for reference
int sum = 0;
int num = number; //Set num equal to number as reference
//reads each digit of the scanned number and individually adds them together
//as it goes through the digits, keep dividing by 10 until its 0.
while (num > 0) {
int lastDigit = num % 10;
sum = sum + lastDigit;
num = num/10;
}
}
}
That is the code I used for calculating the sum of the individual digits, now I just need help with outputting the individual digits. Any tips and tricks would be much appreciated.
import java.util.Scanner;
public class Digits{
public static void main(String args[]) {
//Scans in integer
Scanner stdin = new Scanner(System.in);
System.out.println("Enter in a number: ");
int number = stdin.nextInt();
//Set sum to zero for reference
int sum = 0;
int num = number; //Set num equal to number as reference
//reads each digit of the scanned number and individually adds them together
//as it goes through the digits, keep dividing by 10 until its 0.
String numToString = "";
while (num > 0) {
int lastDigit = num % 10;
numToString +=lastDigit+" + ";
sum = sum + lastDigit;
num = num/10;
}
//eliminate the last + sign
numToString = numToString.substring(0,numToString.lastIndexOf("+")).trim();
System.out.println(numToString +" = " +sum);
}
}
I am not sure what you mean by outputting but instead of this you can read the number as string and take each character and parse it to integers
Scanner stdin = new Scanner(System.in);
System.out.println("Enter in a number: ");
String number = stdin.next();
int[] result = new int[number.length];
for(int i=0;i<number.length;i++) {
result[i] = Integer.parseInt(number.charAt(i)+"");
}
return result;
You may read this like String and then divided by the number.
final Scanner s = new Scanner ( System.in );
final String line = s.nextLine ().trim ();
final char [] array = line.toCharArray ();
int sum = 0;
for ( final char c : array )
{
if ( !Character.isDigit ( c ) )
{
throw new IllegalArgumentException ();
}
sum = sum + Character.getNumericValue ( c );
}
System.out.println ( "sum = " + sum );
without a scanner you can do
StringBuilder sb = new StringBuilder();
String sep = "";
int ch;
long sum = 0;
while((ch = System.in.read()) > ' ') {
if (ch < '0' || ch > '9') {
System.out.println("Skipping " + (char) ch);
continue;
}
sb.append(sep).append((char) ch);
sep = " + ";
sum += ch - '0';
}
sb.append(" = ").append(sum);
System.out.println(sb);
Try this:
import java.util.*;
public class Digits {
public static void main(String [] args)
{
Scanner input = new Scanner (System.in);
System.out.println("Enter number -> ");
int number = input.nextInt();
int sum = 0;
String numStr = "" + number;
while(number > 0)
{
int lastDigit = number % 10;
sum += lastDigit;
number = number / 10;
}
for(int i = 0; i < numStr.length();i++)
{
System.out.print(numStr.charAt(i));
// Dont print an extra + operator at the end
if( i == numStr.length() - 1) continue;
else
System.out.print(" + ");
}
System.out.print(" = " + sum);
}
}
I am trying to convert decimal to binary numbers from the user's input using Java.
I'm getting errors.
package reversedBinary;
import java.util.Scanner;
public class ReversedBinary {
public static void main(String[] args) {
int number;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive integer");
number=in.nextInt();
if (number <0)
System.out.println("Error: Not a positive integer");
else {
System.out.print("Convert to binary is:");
System.out.print(binaryform(number));
}
}
private static Object binaryform(int number) {
int remainder;
if (number <=1) {
System.out.print(number);
}
remainder= number %2;
binaryform(number >>1);
System.out.print(remainder);
{
return null;
} } }
How do I convert Decimal to Binary in Java?
Integer.toBinaryString() is an in-built method and will do quite well.
Integer.toString(n,8) // decimal to octal
Integer.toString(n,2) // decimal to binary
Integer.toString(n,16) //decimal to Hex
where n = decimal number.
Your binaryForm method is getting caught in an infinite recursion, you need to return if number <= 1:
import java.util.Scanner;
public class ReversedBinary {
public static void main(String[] args) {
int number;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive integer");
number = in.nextInt();
if (number < 0) {
System.out.println("Error: Not a positive integer");
} else {
System.out.print("Convert to binary is:");
//System.out.print(binaryform(number));
printBinaryform(number);
}
}
private static void printBinaryform(int number) {
int remainder;
if (number <= 1) {
System.out.print(number);
return; // KICK OUT OF THE RECURSION
}
remainder = number % 2;
printBinaryform(number >> 1);
System.out.print(remainder);
}
}
I just want to add, for anyone who uses:
String x=Integer.toBinaryString()
to get a String of Binary numbers and wants to convert that string into an int. If you use
int y=Integer.parseInt(x)
you will get a NumberFormatException error.
What I did to convert String x to Integers, was first converted each individual Char in the String x to a single Char in a for loop.
char t = (x.charAt(z));
I then converted each Char back into an individual String,
String u=String.valueOf(t);
then Parsed each String into an Integer.
Id figure Id post this, because I took me a while to figure out how to get a binary such as 01010101 into Integer form.
/**
* #param no
* : Decimal no
* #return binary as integer array
*/
public int[] convertBinary(int no) {
int i = 0, temp[] = new int[7];
int binary[];
while (no > 0) {
temp[i++] = no % 2;
no /= 2;
}
binary = new int[i];
int k = 0;
for (int j = i - 1; j >= 0; j--) {
binary[k++] = temp[j];
}
return binary;
}
public static void main(String h[])
{
Scanner sc=new Scanner(System.in);
int decimal=sc.nextInt();
String binary="";
if(decimal<=0)
{
System.out.println("Please Enter greater than 0");
}
else
{
while(decimal>0)
{
binary=(decimal%2)+binary;
decimal=decimal/2;
}
System.out.println("binary is:"+binary);
}
}
The following converts decimal to Binary with Time Complexity : O(n) Linear Time and with out any java inbuilt function
private static int decimalToBinary(int N) {
StringBuilder builder = new StringBuilder();
int base = 2;
while (N != 0) {
int reminder = N % base;
builder.append(reminder);
N = N / base;
}
return Integer.parseInt(builder.reverse().toString());
}
In C# , but it's just the same as in Java :
public static void findOnes2(int num)
{
int count = 0; // count 1's
String snum = ""; // final binary representation
int rem = 0; // remainder
while (num != 0)
{
rem = num % 2; // grab remainder
snum += rem.ToString(); // build the binary rep
num = num / 2;
if (rem == 1) // check if we have a 1
count++; // if so add 1 to the count
}
char[] arr = snum.ToCharArray();
Array.Reverse(arr);
String snum2 = new string(arr);
Console.WriteLine("Reporting ...");
Console.WriteLine("The binary representation :" + snum2);
Console.WriteLine("The number of 1's is :" + count);
}
public static void Main()
{
findOnes2(10);
}
It might seem silly , but if u wanna try utility function
System.out.println(Integer.parseInt((Integer.toString(i,2))));
there must be some utility method to do it directly, I cant remember.
public static void main(String[] args)
{
Scanner in =new Scanner(System.in);
System.out.print("Put a number : ");
int a=in.nextInt();
StringBuffer b=new StringBuffer();
while(a>=1)
{
if(a%2!=0)
{
b.append(1);
}
else if(a%2==0)
{
b.append(0);
}
a /=2;
}
System.out.println(b.reverse());
}
Binary to Decimal without using Integer.ParseInt():
import java.util.Scanner;
//convert binary to decimal number in java without using Integer.parseInt() method.
public class BinaryToDecimalWithOutParseInt {
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
System.out.println("Enter a binary number: ");
int binarynum =input.nextInt();
int binary=binarynum;
int decimal = 0;
int power = 0;
while(true){
if(binary == 0){
break;
} else {
int temp = binary%10;
decimal += temp*Math.pow(2, power);
binary = binary/10;
power++;
}
}
System.out.println("Binary="+binarynum+" Decimal="+decimal); ;
}
}
Output:
Enter a binary number:
1010
Binary=1010 Decimal=10
Binary to Decimal using Integer.parseInt():
import java.util.Scanner;
//convert binary to decimal number in java using Integer.parseInt() method.
public class BinaryToDecimalWithParseInt {
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
System.out.println("Enter a binary number: ");
String binaryString =input.nextLine();
System.out.println("Result: "+Integer.parseInt(binaryString,2));
}
}
Output:
Enter a binary number:
1010
Result: 10
A rather simple than efficient program, yet it does the job.
Scanner sc = new Scanner(System.in);
System.out.println("Give me my binaries");
int str = sc.nextInt(2);
System.out.println(str);
All your problems can be solved with a one-liner!
To incorporate my solution into your project, simply remove your binaryform(int number) method, and replace System.out.print(binaryform(number)); with System.out.println(Integer.toBinaryString(number));.
/**
* converting decimal to binary
*
* #param n the number
*/
private static void toBinary(int n) {
if (n == 0) {
return; //end of recursion
} else {
toBinary(n / 2);
System.out.print(n % 2);
}
}
/**
* converting decimal to binary string
*
* #param n the number
* #return the binary string of n
*/
private static String toBinaryString(int n) {
Stack<Integer> bits = new Stack<>();
do {
bits.push(n % 2);
n /= 2;
} while (n != 0);
StringBuilder builder = new StringBuilder();
while (!bits.isEmpty()) {
builder.append(bits.pop());
}
return builder.toString();
}
Or you can use Integer.toString(int i, int radix)
e.g:(Convert 12 to binary)
Integer.toString(12, 2)
public static String convertToBinary(int dec)
{
String str = "";
while(dec!=0)
{
str += Integer.toString(dec%2);
dec /= 2;
}
return new StringBuffer(str).reverse().toString();
}
Practically you can write it as a recursive function. Each function call returns their results and add to the tail of the previous result. It is possible to write this method by using java as simple as you can find below:
public class Solution {
private static String convertDecimalToBinary(int n) {
String output = "";
if (n >= 1) {
output = convertDecimalToBinary(n >> 1) + (n % 2);
}
return output;
}
public static void main(String[] args) {
int num = 125;
String binaryStr = convertDecimalToBinary(num);
System.out.println(binaryStr);
}
}
Let us take a look how is the above recursion working:
After calling convertDecimalToBinary method once, it calls itself till the value of the number will be lesser than 1 and return all of the concatenated results to the place where it called first.
References:
Java - Bitwise and Bit Shift Operators https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html
If you want to reverse the calculated binary form , you can use the StringBuffer class and simply use the reverse() method . Here is a sample program that will explain its use and calculate the binary
public class Binary {
public StringBuffer calculateBinary(int number) {
StringBuffer sBuf = new StringBuffer();
int temp = 0;
while (number > 0) {
temp = number % 2;
sBuf.append(temp);
number = number / 2;
}
return sBuf.reverse();
}
}
public class Main {
public static void main(String[] args) throws IOException {
System.out.println("enter the number you want to convert");
BufferedReader bReader = new BufferedReader(newInputStreamReader(System.in));
int number = Integer.parseInt(bReader.readLine());
Binary binaryObject = new Binary();
StringBuffer result = binaryObject.calculateBinary(number);
System.out.println(result);
}
}
The better way of doing it:
public static void main(String [] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(bf.readLine().trim());
double ans = 0;
int i=0;
while(t!=0){
int digit = t & 1;
ans = ans + (digit*Math.pow(10,i));
i++;
t =t>>1;
}
System.out.println((int)ans);
}
I just solved this myself, and I wanted to share my answer because it includes the binary reversal and then conversion to decimal. I'm not a very experienced coder but hopefully this will be helpful to someone else.
What I did was push the binary data onto a stack as I was converting it, and then popped it off to reverse it and convert it back to decimal.
import java.util.Scanner;
import java.util.Stack;
public class ReversedBinary
{
private Stack<Integer> st;
public ReversedBinary()
{
st = new Stack<>();
}
private int decimaltoBinary(int dec)
{
if(dec == 0 || dec == 1)
{
st.push(dec % 2);
return dec;
}
st.push(dec % 2);
dec = decimaltoBinary(dec / 2);
return dec;
}
private int reversedtoDecimal()
{
int revDec = st.pop();
int i = 1;
while(!st.isEmpty())
{
revDec += st.pop() * Math.pow(2, i++);
}
return revDec;
}
public static void main(String[] args)
{
ReversedBinary rev = new ReversedBinary();
System.out.println("Please enter a positive integer:");
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine())
{
int input = Integer.parseInt(sc.nextLine());
if(input < 1 || input > 1000000000)
{
System.out.println("Integer must be between 1 and 1000000000!");
}
else
{
rev.decimaltoBinary(input);
System.out.println("Binary to reversed, converted to decimal: " + rev.reversedtoDecimal());
}
}
}
}
import java.util.*;
public class BinaryNumber
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number");
int n = scan.nextInt();
int rem;
int num =n;
String str="";
while(num>0)
{
rem = num%2;
str = rem + str;
num=num/2;
}
System.out.println("the bunary number for "+n+" is : "+str);
}
}
This is a very basic procedure, I got this after putting a general procedure on paper.
import java.util.Scanner;
public class DecimalToBinary {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a Number:");
int number = input.nextInt();
while(number!=0)
{
if(number%2==0)
{
number/=2;
System.out.print(0);//Example: 10/2 = 5 -> 0
}
else if(number%2==1)
{
number/=2;
System.out.print(1);// 5/2 = 2 -> 1
}
else if(number==2)
{
number/=2;
System.out.print(01);// 2/2 = 0 -> 01 ->0101
}
}
}
}
//converts decimal to binary string
String convertToBinary(int decimalNumber){
String binary="";
while(decimalNumber>0){
int remainder=decimalNumber%2;
//line below ensures the remainders are reversed
binary=remainder+binary;
decimalNumber=decimalNumber/2;
}
return binary;
}
One of the fastest solutions:
public static long getBinary(int n)
{
long res=0;
int t=0;
while(n>1)
{
t= (int) (Math.log(n)/Math.log(2));
res = res+(long)(Math.pow(10, t));
n-=Math.pow(2, t);
}
return res;
}
Even better with StringBuilder using insert() in front of the decimal string under construction, without calling reverse(),
static String toBinary(int n) {
if (n == 0) {
return "0";
}
StringBuilder bldr = new StringBuilder();
while (n > 0) {
bldr = bldr.insert(0, n % 2);
n = n / 2;
}
return bldr.toString();
}
No need of any java in-built functions. Simple recursion will do.
public class DecimaltoBinaryTest {
public static void main(String[] args) {
DecimaltoBinary decimaltoBinary = new DecimaltoBinary();
System.out.println("hello " + decimaltoBinary.convertToBinary(1000,0));
}
}
class DecimaltoBinary {
public DecimaltoBinary() {
}
public int convertToBinary(int num,int binary) {
if (num == 0 || num == 1) {
return num;
}
binary = convertToBinary(num / 2, binary);
binary = binary * 10 + (num % 2);
return binary;
}
}
int n = 13;
String binary = "";
//decimal to binary
while (n > 0) {
int d = n & 1;
binary = d + binary;
n = n >> 1;
}
System.out.println(binary);
//binary to decimal
int power = 1;
n = 0;
for (int i = binary.length() - 1; i >= 0; i--) {
n = n + Character.getNumericValue(binary.charAt(i)) * power;
power = power * 2;
}
System.out.println(n);
I am working on a program that needs to calculate the sum of 2 large integers without using the biginteger class in java. I am stuck on my for loop which calculates the sum. I am getting an extra 0 so 30 + 30 = 600.
I am pretty sure it is because I am looping through the arrays the wrong way. I need to go the opposite way (starting from the right side like you would when adding numbers) but I can't seem to fix it without getting an out of array index error.
here is my code:
main:
import java.util.Scanner;
public class testLargeInteger
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String string1;
String string2;
int exp =0;
System.out.print("Enter the first integer: ");
//Store up the input string “string1” entered by the user from the keyboard.
string1 = input.next();
LargeInteger firstInt = new LargeInteger(string1);
System.out.print("Enter the second integer: ");
string2 = input.next();
//Store up the input string “string2” entered by the user from the keyboard.
LargeInteger secondInt = new LargeInteger(string2);
System.out.print("Enter the exponential integer: ");
//Store up the input integer “exp” entered by the user from the keyboard.
exp = input.nextInt();
LargeInteger sum = firstInt.add(secondInt);
System.out.printf ("First integer: %s \n", firstInt.display());
System.out.println("Second integer: " + secondInt.display());
System.out.println(" Exponent: " + exp);
System.out.printf (" Sum = %s \n", sum.display());
}
}
Large integer:
public class LargeInteger {
private int[] intArray;
//convert the strings to array
public LargeInteger(String s) {
intArray = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
intArray[i] = Character.digit(s.charAt(i), 10); // in base 10
}
}
public LargeInteger( int[] array ) {
intArray = array;
}
//display the strings
public String display() {
String result="";
for (int i = 0; i < intArray.length; i++) {
result += intArray[i];
}
return result.toString();
}
//get first array
public int[] getIntArray() {
return intArray;
}
//ADD method to add 2 arrays together
public LargeInteger add(LargeInteger secondInt){
int[] otherValues = secondInt.getIntArray();
int maxIterations = Math.min(intArray.length, otherValues.length);
int currentResult; //to store result
int[] resultArray = new int[Math.max(intArray.length, otherValues.length) +1 ];
int needToAdd = 0; //to store result should be added next step
for(int i = 0; i < maxIterations; i++) {
currentResult = intArray[i] + otherValues[i];
resultArray[i] = currentResult % 10 + needToAdd; //if more than 9 its correct answer
needToAdd = currentResult / 10; //this is what you need to add on next step
}
resultArray[Math.max(intArray.length, otherValues.length) ] = needToAdd;
return new LargeInteger( resultArray );
}
}
I have tried changing the for loop in sum to something like this:
for(int i = maxIterations; i >= 0; i--)
That for loop is only one of your problems.
1] you are not adding the carry properly.
2] a stack is more appropriate here than an array.
With a stack (place code inside your method):
Note: You are calling the function with number.add(num2);
public class LargeInt{
private String number;
public LargeInt(String num){
this.number = num;
}
public String add(String num2){
Stack<Integer> adder = toIntegerStack(this.number);//UPDATE
Stack<Integer> addend = toIntegerStack(num2);//UPDATE
Stack<Integer> result = new Stack<Integer>();
int carry =0;
int tmp = 0;
while(!.adder.isEmpty && !addend.isEmpty()){
tmp = adder.pop()+addend.pop()+carry;
if(tmp > 10){
carry = tmp/10;
tmp%=10;
}else{
carry=0;
}
result.push(tmp);
}//while
while(!adder.isEmpty){
tmp = adder.pop()+carry;
if(tmp > 10){
carry = tmp/10;
tmp%=10;
}else{
carry=0;
}
result.push(tmp);
}//while
while(!addend.isEmpty){
tmp = addend.pop()+carry;
if(tmp > 10){
carry = tmp/10;
tmp%=10;
}else{
carry=0;
}
result.push(tmp);
}//while
//beyond this point the result is your answer
//here convert your stack to string before returning
}
}
UPDATE TO ANSWER COMMENT:
I am also editing above to call this function to fill stacks.
private Stack<Integer> toIntegerStack(String n){
Stack<Integer> stack = new Stack<Integer>();
for(char c: n.toCharArray())
stack.push(c-48);//ASCII
return stack;
}//toStack(String)
If you insist on using array, you must follow the same pattern with your array.
int indexA=0;
int indexB=0;
int[] result = new int[1+A.length>B.length?A.length:B.length];
int indexResult=result.length-1;
while(indexA < A.length && indexB <B.length){//inside is same idea
tmp = A[indexA++] + B[indexB++] + carry;
//... do here as for stacks for tmp and carry
result[indexResult--];
}
while(indexA < A.length){
//do as in stack version
}
while(indexB < B.length){
//do as in stack version
}
Your adding code assumes that the least significant digit is in array[0], but your reading code puts the most significant digit there. You should reverse the array after reading.