题解 | #大数加法#

大数加法

http://www.nowcoder.com/practice/11ae12e8c6fe48f883cad618c2e81475

import java.util.*;

public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * 计算两个数之和 * @param s string字符串 表示第一个整数 * @param t string字符串 表示第二个整数 * @return string字符串 */ public String solve (String s, String t) {

    int slength = s.length();
    int tlength = t.length();
    int sIndex = slength -1;
    int tIndex = tlength -1 ;
    int charLength = slength > tlength ? s.length()+1 : tlength+1;
    int[] chars = new int[charLength]; 
    boolean needMove = false; // 是否需要进位
    while (sIndex >= 0 && tIndex >= 0) {
        int data;
        if (needMove){
        	// char '0' = 48 
            data = (int) s.charAt(sIndex) + (int) t.charAt(tIndex) + 1 - 96;
        } else {
            data = (int) s.charAt(sIndex) + (int) t.charAt(tIndex) - 96;
        }

        if (data < 10) {
            needMove = false;
            chars[--charLength] = data;
        } else {
            needMove = true;
            data -= 10;
            chars[--charLength] = data;
        }
        sIndex--;
        tIndex--;
    }

    while (sIndex >= 0 ){
        int data;
        if (needMove) {
            data = (int) s.charAt(sIndex) + 1 - 48; 
        } else {
            data = (int) s.charAt(sIndex) - 48;
        }

        if (data < 10) {
            needMove = false;
            chars[--charLength] =  data;
        } else {
            needMove = true;
            data -= 10;
            chars[--charLength] =  data;
        }
        sIndex--;
    }

    while (tIndex >= 0 ){
        int data;
        if (needMove) {
            data = (int) t.charAt(tIndex) + 1 - 48;
        } else {
            data = (int) t.charAt(tIndex) - 48;
        }

        if (data < 10) {
            needMove = false;
            chars[--charLength] = data;
        } else {
            needMove = true;
            data -= 10;
            chars[--charLength] = data;
        }
        tIndex--;
    }
    // 还有一个判断
    if (needMove) {
        chars[0] = 1;
    }
    StringBuilder sb = new StringBuilder();
    // 第一个是0的去掉
    boolean flag = true;
    for (int aChar : chars) {
        if (aChar != 0){
            flag = false;
        }
        if (!flag){
            sb.append(aChar);
        }  
    }
    if (sb.length() == 0 ) return "0";
    return sb.toString();
}

}

全部评论

相关推荐

05-12 11:09
已编辑
门头沟学院 后端
已注销:没必要放这么多专业技能的描述。这些应该是默认已会的,写这么多行感觉在凑内容。项目这块感觉再包装包装吧,换个名字,虽然大家的项目基本都是网上套壳的,但是你这也太明显了。放一个业务项目,再放一个技术项目。技术项目,例如中间件的一些扩展和尝试。
简历中的项目经历要怎么写
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务