首頁  >  文章  >  Java  >  java兩個整數相加的實作程式碼

java兩個整數相加的實作程式碼

不言
不言原創
2018-09-12 15:27:202107瀏覽

這篇文章帶給大家的內容是關於java兩個整型相加的實現程式碼 ,有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。

問題描述如下:

Problem Description

I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A B.

參考程式碼如下:

public static void main(String[] args) {
		// TODO Auto-generated method stub
		int s;
		String string1 = null;
		String string2 = null;
		Scanner scanner = new Scanner(System.in);
		string1 = scanner.nextLine();
		System.out.println("the first number:" + string1);
		string2 = scanner.nextLine();
		System.out.println("the second number:" + string2);

		char a1[] = string1.toCharArray();
		int a[] = new int[a1.length];
		for (int i = 0; i < a1.length; i++) {
			a[i] = Integer.valueOf(a1[i]).intValue() - 48;
		}

		char b1[] = string2.toCharArray();

		int b[] = new int[b1.length];
		for (int j = 0; j < b1.length; j++) {

			b[j] = Integer.valueOf(b1[j]).intValue() - 48;

		
		}

		add(a, b);

	}

	public static void add(int c[], int d[]) {

		int temp = 0;
		int e[] = new int[50];
		int c1 = c.length - 1, d1 = d.length - 1, e1 = e.length - 1;

		while (c1 >= 0 && d1 >= 0) {
			if (c[c1] + d[d1] > 9) {
				e[e1] = c[c1] + d[d1] - 10 + temp;
				temp = 1;
			} else {
				e[e1] = c[c1] + d[d1] + temp;
				temp=0;
			}
			c1--;
			d1--;
			e1--;
		}
		while (c1 >= 0 || d1 >= 0) {
			if (c1 >= 0) {
				e[e1] = c[c1] + temp;
				temp=0;
			} else {
				e[e1] = d[d1] + temp;
				temp=0;
			}

			c1--;
			d1--;
			e1--;
		}

		
		System.out.println();
		String sum=Arrays.toString(e);
		System.out.println(sum);

	}

 相關推薦:

#JAVA程式碼實作:AES加密

JAVA實作精確的加減乘除代碼

以上是java兩個整數相加的實作程式碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn