免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1138 | 回复: 0
打印 上一主题 下一主题

面试 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-06-30 11:53 |只看该作者 |倒序浏览
昨天面试一道上机题,惨呀,啥也不会,把题分享下吧,
实现一个任意长度的整数加法。比如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;
            
    }
}


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/92393/showart_1981592.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP