zoukankan      html  css  js  c++  java
  • [LeetCode]415. 字符串相加、43. 字符串相乘

    题目 415. 字符串相加

    给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。

    题解

    维护一个temp表示当前两数相加+上一个进位的和。
    每次更新结果的一位。
    注意终止条件。
    最后将结果串reverse()。

    代码

    class Solution {
        public String addStrings(String num1, String num2) {
            StringBuilder str = new StringBuilder();
            int temp =0;
            int i=num1.length()-1;
            int j=num2.length()-1;
            while(i>=0||j>=0||temp>0){
                int n1 = i>=0? num1.charAt(i--)-'0':0;
                int n2 = j>=0? num2.charAt(j--)-'0':0;
                temp +=n1+n2;
                str.append(temp%10);
                temp/=10;
            }
    
            return str.reverse().toString();
        }
    }
    

    题目 43. 字符串相乘

    题解

    代码

    class Solution {
        public String multiply(String num1, String num2) {
            int len=num1.length()+num2.length();
            int[] res = new int[len];
            for(int i=num1.length()-1;i>=0;--i){
                for(int j = num2.length()-1;j>=0;--j){
                    int tmp = (num1.charAt(i)-'0')*(num2.charAt(j)-'0')+res[i+j+1];//方便进位加入十位统一处理
                    res[i+j+1]=tmp%10;
                    res[i+j]+=tmp/10; //具体看竖试可理解
                }
            }
    
            StringBuilder product = new StringBuilder();
            int begPos = 0;
            while(res[begPos]==0&&begPos<len-1){
                begPos++;
            }
            for(int i=begPos;i<len;++i){
                product.append(res[i]);
            }
            return product.toString();
        }
    }
    
  • 相关阅读:
    爬虫之移动端数据爬取
    Python网络爬虫之图片懒加载技术、selenium和PhantomJS
    iOS-类方法
    iOS-二进制,十进制,十六进制的相互转换
    iOS-category
    iOS-.h和.m文件
    iOS-关于@property和@synthesize
    自定义控件-使用frame和代码的自定义UI控件
    跨平台开发
    GitHub探索
  • 原文地址:https://www.cnblogs.com/coding-gaga/p/12932448.html
Copyright © 2011-2022 走看看