题解 | #大数加法#

大数加法

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();
}

}

全部评论

相关推荐

Southyeung:我说一下我的看法(有冒犯实属抱歉):(1)简历不太美观,给我一种看都不想看的感觉,感觉字体还是排版问题;(2)numpy就一个基础包,机器学习算法是什么鬼?我感觉你把svm那些写上去都要好一点。(2)课程不要写,没人看,换成获奖经历;(3)项目太少了,至少2-3个,是在不行把网上学习的也写上去。
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-07 18:05
哈哈哈哈哈感觉朋友找工作的已经疯掉了,直接上图
码农索隆:真老板娘:“我嘞个去,这不我当年的套路吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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