Heim  >  Artikel  >  Java  >  Java-Implementierungscode zum Addieren zweier Ganzzahlen

Java-Implementierungscode zum Addieren zweier Ganzzahlen

不言
不言Original
2018-09-12 15:27:202107Durchsuche

Der Inhalt dieses Artikels befasst sich mit dem Implementierungscode zum Hinzufügen von zwei Ganzzahlen in Java. Ich hoffe, dass er für Freunde hilfreich ist. Ich habe ein sehr einfaches Problem für Sie. Ihre Aufgabe besteht darin, die Summe von A + B zu berechnen.

Der Referenzcode lautet wie folgt:

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);

	}

Verwandte Empfehlungen :

JAVA-Code-Implementierung: AES-Verschlüsselung

JAVA implementiert präzise Additions-, Subtraktions-, Multiplikations- und Divisionscodes

Das obige ist der detaillierte Inhalt vonJava-Implementierungscode zum Addieren zweier Ganzzahlen. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn