Compute value of string that has numbers seperated by arithmetic operators.

One of my friends recently went to an interview to a very well known startup company. It is supposed to hire only the very best technical people in the industry.  One of the problems that he was asked to write a unit test was,

Suppose a string has numbers separated by arithmetic operators, how do you compute the value of it?

BTW, I personally feel that you are not really testing the knowledge of a person by asking such questions and expecting them to solve it in 6 minutes.

Solution

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Data;

namespace UnitTestProject1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            var operator1= new Operator();
            int result = operator1.Maths("2+3");
            Assert.AreEqual(result, 5);
        }

        [TestMethod]
        public void TestMethod2()
        {
            var operator1 = new Operator();
            int result = operator1.Maths("2+3*4");
            Assert.AreEqual(result, 14);
        }
        [TestMethod]
        public void TestMethod3()
        {
            var operator1 = new Operator();
            int result = operator1.Maths("2+3*10/5");
            Assert.AreEqual(result, 8);
        }
    }

    public class Operator
    {
        public int Maths(string operation)
        {
            object result=new DataTable().Compute(operation, null);
            return Int32.Parse(result.ToString());
        }
    }
}

You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.