Julius Baer Singapore Interview Programming Challenge: How to write a Java Program for String Accumulator? | Technical, Finance, Investment Questions

Julius Baer Singapore Interview Programming Challenge: How to write a Java Program for String Accumulator?

Priya Singh

6 months ago

Introduction: Julius Baer Singapore have asked me to write this Java Program about String Accumulator. They gave around 1.5 Hours to complete the Program.


What is String Accumulator?


1. Create a simple string calculator with a method int add(String numbers).

  a. The method can take 0, 1 or 2 numbers and will return their sum (for an empty string it will return 0) for example “” or “1” or “1,2”.

  b. Start with the simplest test case of an empty string and move to 1 and 2 numbers.

2. Allow the add method to handle an unknown amount of numbers.

3. Allow the add method to handle new lines between numbers (instead of commas).

  a. The following input is ok: “1\n2,3” (will equal 6).

  b. The following input is NOT ok: “1,\n” (don’t need to prove it - just clarifying).

4. Support different delimiters.

  a. To change a delimiter, the beginning of the string will contain a separate line that looks like this: “//<delimiter>\n<numbers…>”, for example “//;\n1;2” should return 3 where the delimiter is ‘;’.

  b. The first line is optional, all existing scenarios should still be supported.

5. Calling add with a negative number will throw an exception with the message “negatives not allowed” - and the negative that was passed. If there are multiple negatives, show all of them in the exception message.

6. Numbers bigger than 1000 should be ignored, so adding 2 + 1001 = 2.

7. Delimiters can be of any length, for example: “//***\n1***2***3” should return 6.

8. Allow multiple delimiters like this: “//delim1|delim2\n” (with a “|” separating delimiters), for example “//*|%\n1*2%3” should return 6.

9. Make sure you can also handle multiple delimiters with length longer than one character.


Problem: How to write a Java Program to generate String Accumulator.


Solution: This Java Program will generate String Accumulator for provided String input.





Java Program:


package com.bo.bjb.service;


import org.apache.logging.log4j.LogManager;

import org.apache.logging.log4j.Logger;

import org.springframework.stereotype.Service;


import java.util.LinkedList;

import java.util.List;


@Service

public class StringAccumulatorService {


  private static final Logger LOGGER = LogManager.getLogger(StringAccumulatorService.class);


  public int add(String numbers) throws Exception {

    LOGGER.info("START ADD : numbers : " + numbers);

    int result = 0;

    if(numbers == null || numbers.trim().length() == 0){

       return result;

    }


    List<String> numberDataList = new LinkedList<>();

    if(numbers.contains("//")){

      int index = numbers.indexOf("\\n");

      LOGGER.info("START ADD : index : " + index);

      String delimeter = numbers.substring(2,index);

      LOGGER.info("START ADD : delimeter : " + delimeter);


      String data = numbers.substring(index+2);

      LOGGER.info("START ADD : data : " + data);


      String[] numberArrayAfterSplittingDelimeter = data.split("\\" + delimeter);

      for(String number: numberArrayAfterSplittingDelimeter){

        if(isNumber(number)){

          numberDataList.add(number);

        }else{

          if(number.contains("\n")){

            String[] numberArrayAfterSplittingNewLine = number.split("\n");

            for(String numberNewLine: numberArrayAfterSplittingNewLine){

              if(isNumber(numberNewLine)){

                numberDataList.add(numberNewLine);

              }

            }

          }

        }

      }

    }else{

      String[] numberArrayAfterSplittingComma = numbers.split(",");

      for(String number: numberArrayAfterSplittingComma){

        if(isNumber(number)){

          numberDataList.add(number);

        }else{

          if(number.contains("\n")){

            String[] numberArrayAfterSplittingNewLine = number.split("\n");

            for(String numberNewLine: numberArrayAfterSplittingNewLine){

              if(isNumber(numberNewLine)){

                numberDataList.add(numberNewLine);

              }

            }

          }

        }

      }

    }


    LOGGER.info("START ADD : numberDataList : " + numberDataList);


    List<String> errorNumbers = new LinkedList<>();

    for(String number: numberDataList){

      if(isNumber(number)){

        int numberValue = Integer.parseInt(number);

        if(numberValue <= 1000){

          if(numberValue < 0){

            errorNumbers.add(number);

          }

          result = result + numberValue;

        }

      }

    }

    LOGGER.info("START ADD : result : " + result);

    LOGGER.info("START ADD : errorNumbers : " + errorNumbers);

    if(!errorNumbers.isEmpty()){

      throw new Exception("Negatives not allowed. Negative Values : " + errorNumbers);

    }

    return result;

  }


  private boolean isNumber(String number){

    try {

      int data = Integer.parseInt(number);

      return true;

    }catch (NumberFormatException e){

      return false;

    }

  }


}



Java Unit Testing:



package com.bo.bjb.service;


import org.junit.jupiter.api.Assertions;

import org.junit.jupiter.api.BeforeEach;

import org.junit.jupiter.api.Test;


import static org.junit.jupiter.api.Assertions.assertEquals;


public class StringAccumulatorServiceTest {


  private StringAccumulatorService orderManagementService;


  @BeforeEach

  public void setup() {

    orderManagementService = new StringAccumulatorService();

  }


  @Test

  public void addTest() throws Exception {

    int result = orderManagementService.add("");

    assertEquals(0,result);

    result = orderManagementService.add("5");

    assertEquals(5,result);

    result = orderManagementService.add("5,7,8");

    assertEquals(20,result);

    result = orderManagementService.add("5,7,8,9");

    assertEquals(29,result);

    result = orderManagementService.add("5\n7,8,9");

    assertEquals(29,result);

  }


  @Test

  public void addTestNumberGreaterThan1000() throws Exception {

    int result = orderManagementService.add("5,7,10004");

    assertEquals(12,result);

    result = orderManagementService.add("10004");

    assertEquals(0,result);

  }


  @Test

  public void addTestNumberDelimiter() throws Exception {

    int result = orderManagementService.add("//;\\n1;2");

    assertEquals(3,result);

    result = orderManagementService.add("//***\\n1***2***3");

    assertEquals(3,result);

  }


  @Test

  public void addTestNegativeInput() {

    Exception exception = Assertions.assertThrows(Exception.class, () -> {

      orderManagementService.add("5,-7,-8");

    });

    Assertions.assertTrue(exception.getMessage().toLowerCase().contains("negatives not allowed"));

  }


}



Priya Singh

Business Analyst at HCL Singapore

6 months ago

Featured Blogs
not found

Category: Investment

Author: Sushmita Pal

Posted : 1 days ago

0( 0 Comments )
not found

Category: Investment

Author: Sushmita Pal

Posted : 3 days ago

60( 0 Comments )
not found

Category: Startup

Author: Anushka Trivedi

Posted : 4 days ago

50( 0 Comments )
not found

Category: Investment

Author: Anushka Trivedi

Posted : 4 days ago

32( 0 Comments )
not found

Category: Investment

Author: Anushka Trivedi

Posted : 4 days ago

64( 0 Comments )
not found

Category: Startup

Author: Anushka Trivedi

Posted : 9 days ago

142( 0 Comments )
not found

Category: Startup

Author: Anushka Trivedi

Posted : 12 days ago

122( 0 Comments )
not found

Category: Technology

Author: Sweety Singh

Posted : 12 days ago

173( 0 Comments )
not found

Category: Stocks

Author: Sweety Singh

Posted : 14 days ago

69( 0 Comments )
not found

Category: Technology

Author: Sweety Singh

Posted : 14 days ago

53( 0 Comments )
Featured Questions
not found

Category: Social

Author: Sweety Singh

Posted : 16 days ago

54( 0 Comments )
not found

Category: Technology

Author: Sweety Singh

Posted : 16 days ago

58( 0 Comments )
not found

Category: Startup

Author: Sweety Singh

Posted : 17 days ago

52( 0 Comments )
not found

Category: Technology

Author: Mahima Choudhari

Posted : 18 days ago

41( 0 Comments )
not found

Category: Technology

Author: Mahima Choudhari

Posted : 18 days ago

54( 0 Comments )
not found

Category: Politics

Author: Ashmit Patel

Posted : 5 months ago

350( 0 Comments )
not found

Category: Social

Author: Ashmit Patel

Posted : 5 months ago

346( 0 Comments )
not found

Category: Politics

Author: Ashmit Patel

Posted : 5 months ago

305( 0 Comments )
not found

Category: Politics

Author: Ashmit Patel

Posted : 5 months ago

337( 0 Comments )
not found

Category: Social

Author: Ashmit Patel

Posted : 5 months ago

253( 0 Comments )