華為機試——兩個超長正整數的加法 java
阿新 • • 發佈:2019-01-29
題目描述:請設計一個演算法完成兩個超長正整數的加法。 要求實現函式: void AddLongInteger(char * pcAddend, char * pcAugend, char * pcAddResult); 輸入引數: char * pcAddend:加數 char * pcAugend:被加數 char * pcAddResult:加法結果 返回值:無 |
|
執行時間限制: | 1 Sec |
記憶體限制: | 128 MByte |
輸入: |
兩個超長正整數的字串 |
輸出: |
相加後結果的字串 |
樣例輸入: |
123456789123456789 123456789123456789 |
樣例輸出: |
246913578246913578 |
- import java.util.Arrays;
- import java.util.Scanner;
- publicclass Main {
- publicstaticvoid main(String[] args) {
- // TODO Auto-generated method stub
- Scanner sc = new Scanner(System.in);
- char[] a1 = sc.next().toCharArray();
-
char
- char[] result = AddLongInteger(a1,a2);
- for(int i = 0;i < result.length;i++){
- System.out.print(result[i]);
- }
- }
- /*
- * AddLongInteger(char[] a1, char[] a2)的思想:
-
* 首先:a1[0]對應的是第一個被加數的最高位,a2[0]同樣,所以做加法的時候應該從a1[a1.length-1]位開始,或者將a1前後轉置
- * 然後加法的計算是:(a1[1]+a2[1]+進位)%10 進位=(a1[1]+a2[1]+進位)/10
- * 然後就是字元與數字之前的轉換,千萬不要搞混
- */
- publicstaticchar[] AddLongInteger(char[] a1, char[] a2){
- int len=0;
- if(a1.length > a2.length){
- len = a1.length + 1;
- }else{
- len = a2.length + 1;
- }
- char[] temp = newchar[len];
- char[] result;
- char[] b1 = newchar[a1.length];
- char[] b2 = newchar[a2.length];
- for(int i = 0;i < a1.length;i++){
- b1[a1.length - 1 - i] = a1[i];
- }
- for(int i = 0;i < a2.length;i++){
- b2[a2.length - 1 - i] = a2[i];
- }
- for(int i = 0; i < temp.length; i++){
- temp[i] = '0';
- }
- for(int i = 0; i < len-1;i++){
- int res = 0;
- if(b1.length -1 - i >=0 && b2.length -1 - i >= 0){
- res = b1[i] - '0' + b2[i] - '0';
- }elseif(b1.length -1 - i >= 0 && b2.length -1 - i < 0){
- res = b1[i] - '0';
- }elseif(b1.length -1 - i < 0 && b2.length -1 - i >= 0){
- res = b2[i] - '0';
- }
- int value = temp[i]-'0'+res;
- temp[i] = (char) (value%10 + '0') ;
- temp[i+1] += value/10;
- // System.out.println(temp[i]);
- // System.out.println(temp[i+1]);
- }
- while(temp[len - 1] == '0'){
- len--;
- }
- result = newchar[len];
- int s = result.length;
- for(int i = 0;i < s; i++){
- result[s-1-i] = temp[i];
- }
- return result;
- }
- }