Click here to Skip to main content
15,886,788 members
Please Sign up or sign in to vote.
2.00/5 (4 votes)
See more:
Its asked me in interview

2 strings

string s="1234566633434"

string s2="8934343433"

need to sum it without casting

only in string

How to do it
thanks
Posted
Comments
Mohd. Mukhtar 22-Nov-12 2:22am    
string s3 = s + s2;
Sergey Alexandrovich Kryukov 22-Nov-12 2:38am    
Right! No casting... :-)
--SA

It's an exercise in how you think.

What you would need to have done is basically long addition: work though both strings from the right hand end adding the value of each character, and setting the output digit and the carry appropriately.

Basically, the same process you probably used when they were teaching you to add large numbers at school...
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 22-Nov-12 3:00am    
Very nice, a 5.
--SA
just add number "zero"

In VB

Dim a, b, c As String
a = "1"
b = "2"
c = 0 + a + b
Response.Write("c=" + C)
 
Share this answer
 
Comments
OriginalGriff 22-Nov-12 3:05am    
Um. Two problems:
1) That involves implicit casting. The compiler writes it in for you.
2) The question was clearly tagged as "C#" where that won't work. One of the big advantages of C# over VB in the real world!
Sorry - gets my vote of one.
pryashrma 22-Nov-12 4:14am    
Thanks for your comments
OriginalGriff 22-Nov-12 4:30am    
You're welcome!
C#
static class Program
    {
        static void Main()
        {
            const string s = "1234566633434";
            const string s2 = "8934343433";
            //Console.WriteLine(long.Parse(s) + long.Parse(s2));
            Console.WriteLine(ToLong(s) + ToLong(s2));
        }



        private static long ToLong(string str)
        {
            long num = 0;
            var sign = false;
            if (IsDigit(str))
            {
                if (str[0] == '-') sign = true;

                num = str
                    .Where(q => q != '-')
                    .Aggregate(num, (current, item) => current * 10 + item - '0');
            }
            return sign ? -num : num;
        }

        private static bool IsDigit(string str)
        {
            return Regex.IsMatch(str, @"^-?\d+$");
        }

    }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900