Loop to add string of number

╄→尐↘猪︶ㄣ 提交于 2020-03-25 12:32:34

问题


I try for an exercice to add

String nb = "135";
String nb2 = "135";

Result should be a String of "270"

I have no idea how to do that...I try to make a for loop and make an addition : nb.charAt(i) + nb2.charAt(i) but with no succes, I don't know what I have to do with the carry over.

EDIT : I try to don't use Integer or BigInteger, only String this is why I try to use a for loop.

Thanks for clue.


回答1:


String str = "";

// Calculate length of both String  
int n1 = nb.length(), n2 = nb2.length();  
int diff = n2 - n1;  

// Initially take carry zero  
int carry = 0;  

// Traverse from end of both Strings  
for (int i = n1 - 1; i>=0; i--)  
{  
    // Do school mathematics, compute sum of  
    // current digits and carry  
    int sum = ((int)(nb.charAt(i)-'0') +  
        (int) nb2.charAt(i+diff)-'0') + carry);  
    str += (char)(sum % 10 + '0');  
    carry = sum / 10;  
}  

// Add remaining digits of nb2[]  
for (int i = n2 - n1 - 1; i >= 0; i--)  
{  
    int sum = ((int) nb2.charAt(i) - '0') + carry);  
    str += (char)(sum % 10 + '0');  
    carry = sum / 10;  
}  

// Add remaining carry  
if (carry > 0)  
    str += (char)(carry + '0');  

// reverse resultant String 
return new StringBuilder(str).reverse().toString();



回答2:


You need to convert the strings to numbers to add them. Let's use BigInteger, just in case the numbers are really big:

String nb  = "135";
String nb2 = "135";

BigInteger num1 = new BigInteger(nb);
BigInteger num2 = new BigInteger(nb2);

String result = num1.add(num2).toString();



回答3:


Do it as follows:

public class Main {
    public static void main(String args[]) {
        System.out.println(getSum("270", "270"));
        System.out.println(getSum("3270", "270"));
        System.out.println(getSum("270", "3270"));
    }

    static String getSum(String n1, String n2) {
        StringBuilder sb = new StringBuilder();
        int i, n, cf = 0, nl1 = n1.length(), nl2 = n2.length(), max = nl1 > nl2 ? nl1 : nl2, diff = Math.abs(nl1 - nl2);

        for (i = max - diff - 1; i >= 0; i--) {
            if (nl1 > nl2) {
                n = cf + Integer.parseInt(String.valueOf(n1.charAt(i + diff)))
                        + Integer.parseInt(String.valueOf(n2.charAt(i)));
            } else {
                n = cf + Integer.parseInt(String.valueOf(n1.charAt(i)))
                        + Integer.parseInt(String.valueOf(n2.charAt(i + diff)));
            }
            if (n > 9) {
                sb.append(n % 10);
                cf = n / 10;
            } else {
                sb.append(n);
                cf = 0;
            }
        }
        if (nl1 > nl2) {
            for (int j = i + 1; j >= 0; j--) {
                sb.append(n1.charAt(j));
            }
        } else if (nl1 < nl2) {
            for (int j = i + 1; j >= 0; j--) {
                sb.append(n2.charAt(j));
            }
        }
        return sb.reverse().toString();
    }
}

Output:

540
3540
3540



回答4:


Try this i hope it works for you

Code

public static int convert_String_To_Number(String numStr,String numStr2) {
                char ch[] = numStr.toCharArray();
                char ch2[] = numStr2.toCharArray();
                int sum1 = 0;
                int sum=0;
                //get ascii value for zero
                int zeroAscii = (int)'0';
                for (char c:ch) {
                    int tmpAscii = (int)c;
                    sum = (sum*10)+(tmpAscii-zeroAscii);

                }
for (char d:ch2) {
                    int tmpAscii = (int)d;
                    sum1 = (sum*10)+(tmpAscii-zeroAscii);

                }

                return sum+sum1;
            }
            public static void main(String a[]) {
                System.out.println("\"123 + 123\" == "+convert_String_To_Number("123" , "123"));

            }
        }



回答5:


try below snippet:

String s1 = "135";
    String s2 = "135";
    String result = Integer.toString (Integer.parseInt(s1)+Integer.parseInt(s2));



回答6:


try converting char to int using Integer.parseInt(nb.charAt(i)) + Integer.parseInt(nb2.charAt(i))




回答7:


you can use Character.numericValue to give you the integer value of a character, this will probably help you write the method. This method will also return -1 if there is no numeric value or -2 if it is fractional like the character for 1/2




回答8:


I would like to propose a much cleaner solution that adds 2 positive numbers and returns the result. Just maintain a carry while adding 2 digits and add carry in the end if carry is greater than 0.

public class Main{
    public static void main(String[] args) {
        System.out.println(addTwoNumbers("135","135"));
    }

    private static String addTwoNumbers(String s1,String s2){
        if(s1.length() < s2.length()) return addTwoNumbers(s2,s1);
        StringBuilder result = new StringBuilder("");
        int ptr2 = s2.length() - 1,carry = 0;
        for(int i=s1.length()-1;i>=0;--i){
             int res = s1.charAt(i) - '0' + (ptr2 < 0 ? 0 : s2.charAt(ptr2--) - '0') + carry;
             result.append(res % 10);
             carry = res / 10;
        }

        if(carry > 0)  result.append(carry);
        return trimLeadingZeroes(result.reverse().toString());
    }

    private static String trimLeadingZeroes(String str){
        for(int i=0;i<str.length();++i){
            if(str.charAt(i) != '0') return str.substring(i); 
        }

        return "0";
    }
}

Demo: https://onlinegdb.com/Sketpl-UL



来源:https://stackoverflow.com/questions/60757693/loop-to-add-string-of-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!