zoukankan      html  css  js  c++  java
  • 415. Add Strings

    Given two non-negative numbers num1 and num2 represented as string, return the sum of num1 and num2.
    
    Note:
    
    The length of both num1 and num2 is < 5100.
    Both num1 and num2 contains only digits 0-9.
    Both num1 and num2 does not contain any leading zero.
    You must not use any built-in BigInteger library or convert the inputs to integer directly.
    public class Solution {
        public String addStrings(String num1, String num2) {
            StringBuffer res = new StringBuffer();
            int i = num1.length()-1;
            int j = num2.length()-1;
            int carry = 0;
            while (i>=0 || j>=0 || carry!=0) {
                int sum = 0;
                if (i >= 0) {
                    sum += (int)(num1.charAt(i) - '0');
                    i--;
                }
                if (j >= 0) {
                    sum += (int)(num2.charAt(j) - '0');
                    j--;
                }
                if (carry != 0) {
                    sum += carry;
                }
                int digit = sum % 10;
                carry = sum / 10;
                res.insert(0, digit);
            }
            return res.toString();
        }
    }
    

     carry sum 处理字符串的运算问题,  在转化成数值: (int) (num1.charAt(i) - '0') 转换成数值(同 Character.getNumericValue(char a) ), 非ASCII 码. 再 转化成字符.

    也常转化成AScII 码, 在转换成字符串, 所以看看是要数值还是要字符, 还是要数值字符

  • 相关阅读:
    checkbox美化
    JS 之简单计算器
    python实现简单用户认证和角色制授权
    搭建高性能web服务
    纯JS实现fadeIn 和fadeOut
    纯CSS实现气泡框
    javascript之对象(二)&& 继承问题
    JavaScript之对象(一)
    Web发展史
    [LeetCode 256] Paint House
  • 原文地址:https://www.cnblogs.com/apanda009/p/7159071.html
Copyright © 2011-2022 走看看