Chinaunix首页 | 论坛 | 博客
  • 博客访问: 11616
  • 博文数量: 9
  • 博客积分: 290
  • 博客等级: 二等列兵
  • 技术积分: 100
  • 用 户 组: 普通用户
  • 注册时间: 2009-02-04 15:47
文章分类
文章存档

2009年(9)

我的朋友
最近访客

分类: Java

2009-06-30 11:53:15

昨天面试一道上机题,惨呀,啥也不会,把题分享下吧,
实现一个任意长度的整数加法。比如3000位数该如何计算?
 

import java.util.Scanner;


public class VeryBigNumAdd {

    /**
     * @param args
     */

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        VeryBigNumAdd vbn = new VeryBigNumAdd();
        Scanner in = new Scanner(System.in);
        System.out.println("请输入两个数字:");
        
        String a=in.nextLine();
        String b=in.nextLine();
        String result = vbn.doAdd(a,b);
        System.out.println("result:"+result);

    }
    
    String doAdd(String a,String b){
        String str="";
        int maxLen;
        int minLen;
        int lenA=a.length();
        int lenB=b.length();
        if(lenA>lenB){
            maxLen=lenA;
            minLen=lenB;
        }else{
            maxLen=lenB;
            minLen=lenA;
        }


        String strTmp="";
        for(int i=maxLen-minLen;i>0;i--){
            strTmp+="0";
        }
                //把长度调整到相同的长度

        if(maxLen==lenA)
            {b=strTmp + b;}
        else
        a=strTmp + a;
        int JW=0;
        for(int i=maxLen-1;i>=0;i--)
        {
            int tempA = Integer.parseInt(String.valueOf(a.charAt(i)));
            int tempB = Integer.parseInt(String.valueOf(b.charAt(i)));
            int temp;
            if(tempA+tempB+JW>=10&&i!=0){
                temp=tempA+tempB+JW-10;
                JW=1;
            }else{
                temp=tempA+tempB+JW;
                JW=0;
            }
            str=String.valueOf(temp)+str;
        }
        
        return str;
            
    }

}

阅读(475) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~