由lintcode 655题引发的小思考

来源:互联网 发布:翻牌抽奖软件 编辑:程序博客网 时间:2024/05/22 05:27

Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.

十分基础的一道题,通过将字符串转化为数字进行计算后再转化为字符串输出。

答案代码如下:

public class Solution {    /*     * @param num1: a non-negative integers     * @param num2: a non-negative integers     * @return: return sum of num1 and num2     */    public String addStrings(String num1, String num2) {        // write your code here        if(num1.equals("0"))            return num2;        if(num2.equals("0"))            return num1;        int len1 = num1.length();        int len2 = num2.length();        int len = (len1>len2)?len1:len2;        char[] result = new char[len+1];        for(int i=0;i<=len;i++){            result[i] = '0';        }        int a=0;        int b=0;        int c=0;        String res="";        for(int i=0;i<=len;i++){            if(i<len1){                a = num1.charAt(len1-1-i)-'0';            }else{                a = 0;            }            if(i<len2){                b = num2.charAt(len2-1-i)-'0';            }else{                b = 0;            }            int total = a+b+c;            c = total%10;            result[len-i]=(char)(c+'0');            if(total>9)                c=1;            else                c=0;        }        if(!(result[0]=='0')){            res+=result[0];        }        for(int i=1;i<=len;i++){            res+=result[i];        }        return res;    }}

该道题的解题思路是通过charAt()这一方法将字符串中的字符一个个拆分出来,并通过调整ASCII码将char类型的数字强制转化为int类型的数字。

第一次的问题出在char转化为int的时候,由于一开始没有加-‘0’这个操作,得出来的结果其实是数字的ASCII码,只有减去‘0’这个ASCII码之后才能真正的得到想要的数字。反之int想转化为char的时候则要加上‘0’,这也是这道题所获得的第一个收获。

第二个收获则是charAt()这一方法的参数范围是0到(length-1),值得注意的一个小知识点。另外,声明数组时,数组的范围也是0到(参数-1)