当前位置:网站首页>Niuke daily question -day1

Niuke daily question -day1

2022-06-12 05:37:00 Violence produces miracles

Add big numbers

Title Description
Read in two numbers as a string , Write a function to calculate their sum , Returns... As a string .
( The string length is not greater than 100000, Ensure that the string consists only of ’0’~'9’ this 10 Characters make up )
Example 1
Input

“1”,“99”
Return value
“100”
explain
1+99=100

type , simulation , difficulty , samsung , Time consuming 20 minute

My solution : Use three stacks + A little simulation thinking

import java.util.*;


public class Solution {
    
    /** *  The class name in the code 、 Method name 、 The parameter name has been specified , Do not modify , Return the value specified by the method directly  *  Calculate the sum of two numbers  * @param s string character string   Represents the first integer  * @param t string character string   Represents the second integer  * @return string character string  */
    public String solve (String s, String t) {
    
        // write code here
        Stack<Integer> stack1 = new Stack();
        Stack<Integer> stack2 = new Stack();
        if(s.length()<t.length()){
    
            String temp =s;
            s=t;
            t=temp;
        }
        for(int i=0;i<s.length();i++){
    
            stack1.push(s.charAt(i)-'0');
        }
        for(int i=0;i<t.length();i++){
    
            stack2.push(t.charAt(i)-'0');
        }
        int te=0;
        Stack<Integer> res = new Stack();
        while(!stack1.isEmpty()&&!stack2.isEmpty()){
    
            int a=stack1.pop();
            int b=stack2.pop();
            int c=a+b+te;
            if(c>=10){
    
                te=c/10;
                c=c%10;
            }else{
    
                te=0;
            }
            res.push(c);
        }
        while(!stack1.isEmpty()){
    
            int a=stack1.pop();
            int b=te;
            int c=a+b;
            if(c>=10){
    
                te=c/10;
                c=c%10;
            }else{
    
                te=0;
            }
            res.push(c);
        }
        if(te>0){
    
            res.push(te);
        }
        StringBuilder str = new StringBuilder();
        while(!res.isEmpty()){
    
            str.append(String.valueOf(res.pop()));
        }
        return str.toString();
    }
}
原网站

版权声明
本文为[Violence produces miracles]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203010615381639.html