×

Least Operator to Express Number in Java

In this article, we will learn about how to obtain a target number using a single number or a single integer by leveraging least operators in Java. There can be many expressions that can bring out the target number but the expression with least or the minimum operators need to be found.

We must construct an equation or formula that comprises only the digit D and that evaluates to the number N given an integer N and the digit D. The operators +, -, *, or / may be used in expressions. Find the least number of operators that satisfy the requirement that D only exist in the expression 10(limit) times or less. Limit the N values as a result. Although how much further you want to go determines the value of limit. However, the below approach may take longer if the limit is large. Keep in mind that there may be more than just one minimal expression of D that equals N, however the expression with fewest operators must be chosen.

Let us understand more clearly with the examples.

Example 1

 N = 7, D = 3

 3/3+ 3 + 3

Interpretation: 3/3 = 1, and 1+3+3 = 7

The least operators required are 3.

Example 2

N = 501, D = 5

Interpretation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5.

The least operators required are 8.

Example 3

N = 7, D =4

Interpretation: (4+4+4)/4 +4

The least operators required are 4.

Let us understand it with a program.

File name : Solution.java

class Solution {
    Map<Integer, Integer> memo = new HashMap<>();
    public int leastOpsExpressTarget(int x, int target) {
        if (target == 1) 
            return x == 1 ? 0 : 1;
        if (memo.containsKey(target))
            return memo.get(target);
        long product = x;
        int count = 0;
        while (product < target) {
            count++;
            product *= x;
            
        }
        
        // candidate1 : in the form : x*x*...*x - (......) = target
        int cand1 = Integer.MAX_VALUE;
        if (product == target)
            cand1 = count;
        else if (product - target < target)
            cand1 = count + leastOpsExpressTarget(x, (int)(product - target)) + 1;
        
        // candidate2 : in the form : x*x*...*x + (......) = target
        int cand2 = Integer.MAX_VALUE;
        product /= x;
        cand2 = leastOpsExpressTarget(x, (int)(target - product)) + (count == 0 ? 2 : count);
        int res = Math.min(cand1, cand2);
        memo.put(target, res);
        return res;
    }
}

The above is the approach or the algorithm in Java, that can obtain the least count of operators as output.

Input

N = 501, D =5

Output

The expression contains 8 operations.

Input

N = 19, D = 3

Output

The expression contains 5 operations.

The Approach

Divided by (/), rational numbers are returned. There isn’t any parenthesis anywhere in the text. We follow the standard order of operations, with addition and subtraction coming after multiplication and division. Use of the unary negation operator is prohibited (-). For instance, "-x + x" is not a valid expression since it involves negation, but "x - x" is because it just uses subtraction. In order to create an expression that equals the specified target, we want to use the fewest possible operators. Give the least number of operators.

We employ a backtracking strategy. Starting with the provided Digit D, we multiply, add, subtract, add, and divide as much as we can. This method is continued until the sum equals N or until we arrive at the conclusion and turn around to begin a new path. We locate the recursive tree's lowest level in order to determine the smallest expression. utilize the backtracking algorithm after that. Then the program makes the count of the number of operators employed to bring out the desired output.

Note: If there exist expressions with same number of operators in them, anyone will be chosen among them. Both the expressions are valid.

Every level has four additional recursions (at-most). We may therefore claim that the approach has a temporal complexity of 4n, where n represents the number of levels in the recursion trees. Alternatively, we can specify the maximum number of times D should appear in the expression, in this example 10, which is ten.


Related Topics

How to Create an API in Java?

Introduction The API can be abbreviated as Application Programming Interface. An API is a combination of set of classes and interfaces. It is also equivalent to a simple java program. To...

12 minutes read.

Java Binary Operators

In this article, we are going to discuss about the binary operators in Java and their operations. Also, an example program will be discussed along with the operations. These are...

6 minutes read.

Objects and Classes in Java

Objects and Classes in Java Classes and objects are the basic concepts of object-oriented programming. It revolves around the real world entity. In Java, the object is a physical and logical...

5 minutes read.

Star Pattern Programs in Java

Star Pattern Programs in Java The star pattern programs in Java is the part of pattern programs in Java, which we discussed earlier. Right Triangle Star Pattern Filename: StarPatternExample.java public class StarPatternExample {              public static void...

4 minutes read.

How to Convert Octal to Decimal in Java

How to Convert Octal to Decimal in Java There are two methods to convert Octal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method The Integer.parseInt() method is a static method...

2 minutes read.

Add Time in Java

Before Java 8, java.util.Date was one of the most usually involved classes for addressing date-time values in java. Then Java 8 presented java.time.LocalDateTime and java.time.ZonedDateTime. Java 8 likewise permits us...

6 minutes read.

How to Update Java

As we all know that java can be installed in all operating systems like windows, Linux, macOS. We are available with the java 17 and java 18 versions in the...

3 minutes read.

PriorityBlockingQueue Class in Java

What is the Queue? An abstract data structure like Stacks is a queue. A queue is open on both ends. Data is always pushed to one end, called enqueue, and removed...

4 minutes read.

Hogben Numbers in Java

In this section, we will discover what the Hogben number is and develop Java programs that compute it. Java coding interviews and academic exams typically involve questions about the Hogben...

3 minutes read.

What is advance Java?

The definition of advance inside the dictionary refers to a forward motion, development, or progress, and the definition of enhancing is something that improves things. To become experts in that...

3 minutes read.

String Coding Interview Questions in Java

What is String in Java?In Java, a String is a Class that is defined in the java.lang package. It isn't a basic data type like int or long. Character Strings...

5 minutes read.

Java Integer signum() method

The signum() method of Java Integer class returns the signum function of the specified int value. Syntax public static int signum (int i)  Parameters The parameter ‘i’ represents the value whose signum is to...

1 minute read.

Java instance variable

An instance in object-oriented programming (OOP) is a particular implementation of any object. Each realized version of an item, which might vary in several ways, is an instance. Instantiation is...

3 minutes read.

Upcasting in Java

To know what is Upcasting in Java we should first equip ourselves about what is casting or type casting in Java. Casting The process of providing or replacing a reference variable of...

3 minutes read.

Object Definition in Java

In this article, you will be acknowledged about object in Java, its definition and how is this useful in writing the programs in Java. The comprehension of object-oriented technology depends on...

4 minutes read.

Java Comparator Interface

Java comparator interface is used in a situation when we have to sort an object which does not implement Comparable or do sorting in a different way than the Comparable....

1 minute read.

Thread Program in Java

Thread Program in Java Thread program in Java is the continuation of multithreading program in Java. In this topic, we will learn about the usage of threads, race condition in multithreading,...

8 minutes read.

How to Convert Hexadecimal to Decimal in Java

How to Convert Hexadecimal to Decimal in Java There are two methods to convert Hexadecimal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method It is a static method of...

2 minutes read.

Java Xml Parser

In this article, we acknowledge you about what is a XML parser in Java, how is it going to work and what is the purpose of it. Also, the article discusses...

6 minutes read.

Java Variable Declaration

In this article, you will be acknowledged about java variable declaration. You will be able to learn and interpret about declaring a variable in Java. Variable in Java Variables are necessary for...

6 minutes read.