大数的加法

来源:互联网 发布:炫舞房间源码 编辑:程序博客网 时间:2024/06/06 09:03

只是实现了两个位数相等的大数的相加,若要两个不同的数相加可以修改一下逻辑,粗浅的很,请多指教

/**
  *
  * @param a
  * @param b
  * @return 以字符串形式返回结果
  */
 public static String add(String a, String b) {
  String result = "";
  int temp = 0;// 临时存放每个位数上的和
  int[] cun = new int[LEN];// 将结果存放到数组中
  boolean flag = false;//判断是否有进位
  //这个for循环用于将和存放到数组中
  for (int i = LEN - 1; i >= 0; i--) {//从个位数开始循环
   // 将字符转化成int
   // temp=Integer.parseInt(a.charAt(i)+"")+Integer.parseInt(a.charAt(i)+"");
   temp = Integer.parseInt(String.valueOf(a.charAt(i)))//a在i位上的值
     + Integer.parseInt(String.valueOf(b.charAt(i)));//b在i位上的值
   if (i == 0) {//最高位数的相加的特殊情况
    if (flag) {
     cun[i] = temp + 1;
    } else {
     cun[i] = temp;
    }
   } else {
    if (temp >= 10) {// 当这个位数上的数需要进位时
     if (flag) {      
      cun[i] = temp % 10 + 1;// 这个位数上的数有进位
     } else {
      cun[i] = temp % 10;
     }
     flag = true;
    } else {
     if (flag) {
      if((temp + 1)>9){//如果有进位且相加后等于10的情况
       cun[i]=0;
       flag=true;
      }
      else{
       cun[i] = temp + 1;// 这个位数上的数有进位
      }  
     } else {
      cun[i] = temp;
     }
     flag = false;
    }
   }
  }
  for (int j = 0; j < LEN; j++) {
   //System.out.println(cun[j]);
   result = result + cun[j];
  }
  return result;
 }

 

 

0 0
原创粉丝点击