search
HomeJavajavaTutorialPrint the binary representation of an integer in Java using recursion

Print the binary representation of an integer in Java using recursion

Recursion is a powerful programming technique that works by breaking a problem into smaller, more tractable sub-problems and applying the same algorithm to solve them. In the world of Java programming, recursion proves to be an invaluable tool for printing binary representations of integers. The binary equivalent, expressed in a base-2 number system with only two digits 0 and 1, presents a common challenge in the field.

In this article, we will set out to shed light on the complexities of printing the binary equivalent of an integer using recursion in Java. Our exploration will include an in-depth examination of syntax, algorithms, and two different methods that can be used to accomplish this task. The initial approach involves using helper methods to concatenate with strings, while the second approach requires the use of a "StringBuilder" for efficient string concatenation. In this article, we provide comprehensive code examples along with output to illustrate the implementation and utilization of these methods.

method

  • Method 1 - Auxiliary method with string concatenation

  • Method 2 − StringBuilder for string concatenation

grammar

public class BinaryPrinter {
   public static void printBinary(int n) {
      if (n > 0) {
         printBinary(n / 2);
         System.out.print(n % 2);
      }
   }

   public static void main(String[] args) {
      int num = 10; // Example input
      System.out.print("Binary equivalent of " + num + " is: ");
      printBinary(num);
   }
}

algorithm

The complexity of printing the binary equivalent of an integer using recursion is as follows -

  • Step 1 - Make a method called "printBinary" that accepts an integer "n" as input.

  • Step 2 - In the "printBinary" method, evaluate whether "n" exceeds 0.

  • Step 3 − If 'n' is greater than 0, use 'n' divided by 2 as input and call the 'printBinary' method recursively.

  • Step 4 - After the recursive call, generate the binary number at the current position by printing the remainder of 'n' divided by 2.

  • Step 5 - Keep repeating steps 3-4 until 'n' reaches 0, which will serve as the base case for recursion.

  • method one

    In this innovative approach, we use a helper method called 'printBinaryHelper', which contains an extra parameter marked 'binary', which is a string. When we call the 'printBinaryHelper' method recursively, we cleverly concatenate the remainder of 'n' divided by 2 with the existing 'binary' string, creating a seamless integration. Once the value of 'n' reaches 0, we proudly print out the final 'binary' string, which elegantly symbolizes the binary representation of the input integer.

    The following is the same program code.

    The Chinese translation of

    Example-1

    is:

    Example-1

    public class BinaryPrinter {
       public static void printBinary(int n) {
          printBinaryHelper(n, "");
       }
    
       public static void printBinaryHelper(int n, String binary) {
          if (n > 0) {
             printBinaryHelper(n / 2, n % 2 + binary);
          } else {
             System.out.println("Binary equivalent: " + binary);
          }
       }
    
       public static void main(String[] args) {
          int num = 10; // Example input
          System.out.print("Binary equivalent of " + num + " is: ");
          printBinary(num);
       }
    }
    

    Output

    Binary equivalent of 10 is: Binary equivalent: 1010
    

    Method 2

    In this innovative approach, we use 'StringBuilder' to accurately track complex binary numbers while calling the 'printBinary' method recursively. 'StringBuilder' proves to be an efficient string concatenation tool without the need to create additional string objects, thereby enhancing performance compared to traditional string concatenation methods. After the recursive process successfully completes, the 'StringBuilder' is converted to a string representation, showing the binary equivalent of the input integer, in a fascinating display of technical prowess.

    The following is the same program code.

    The Chinese translation of

    Example-2

    is:

    Example-2

    public class BinaryPrinter {
       public static void printBinary(int n) {
          System.out.print("Binary equivalent: ");
          StringBuilder binary = new StringBuilder();
          printBinaryHelper(n, binary);
          System.out.println(binary.toString());
       }
    
       public static void printBinaryHelper(int n, StringBuilder binary) {
          if (n > 0) {
             printBinaryHelper(n / 2, binary);
             binary.append(n % 2);
          }
       }
    
       public static void main(String[] args) {
          int num = 10; // Example input
          System.out.print("Binary equivalent of " + num + " is: ");
          printBinary(num);
       }
    }
    

    Output

    Binary equivalent of 10 is: Binary equivalent: 1010
    

    in conclusion

    Recursion is a powerful technique in programming, showing its power in solving a variety of tasks, including printing the binary representation of an integer in Java. In this comprehensive tutorial, we explore two different approaches to achieving optimal recursion using string concatenation and the powerful `StringBuilder`. With a deep understanding of the syntax, algorithms, and skillful implementation of these methods, you can now easily use the power of recursion to print binary representations of integers in Java. As you begin this coding journey, carefully choose an approach that is compatible with your unique needs and consider the performance impact that string concatenation may have in your application. Armed with these insights, you can master the art of recursion in Java programming and unleash the full potential of this powerful technique in your coding efforts.

The above is the detailed content of Print the binary representation of an integer in Java using recursion. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
带你搞懂Java结构化数据处理开源库SPL带你搞懂Java结构化数据处理开源库SPLMay 24, 2022 pm 01:34 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

Java集合框架之PriorityQueue优先级队列Java集合框架之PriorityQueue优先级队列Jun 09, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

完全掌握Java锁(图文解析)完全掌握Java锁(图文解析)Jun 14, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

一起聊聊Java多线程之线程安全问题一起聊聊Java多线程之线程安全问题Apr 21, 2022 pm 06:17 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

Java基础归纳之枚举Java基础归纳之枚举May 26, 2022 am 11:50 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

详细解析Java的this和super关键字详细解析Java的this和super关键字Apr 30, 2022 am 09:00 AM

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

Java数据结构之AVL树详解Java数据结构之AVL树详解Jun 01, 2022 am 11:39 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于平衡二叉树(AVL树)的相关知识,AVL树本质上是带了平衡功能的二叉查找树,下面一起来看一下,希望对大家有帮助。

java中封装是什么java中封装是什么May 16, 2019 pm 06:08 PM

封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),