Open In App

How to convert given number to a character array

Improve
Improve
Like Article
Like
Save
Share
Report

Given an integer number N, the task is to convert it into a character array.

Example:  

Input: N = 2020 
Output: {2, 0, 2, 0} 
Explanation: Here char array arr[] = {2, 0, 2, 0}
Input: N = 12349 
Output: {1, 2, 3, 4, 9} 
Explanation: Here char array arr[] = {1, 2, 3, 4, 9}

 

Approach 1:  The basic approach to do this, is to recursively find all the digits of N, and insert it into the required character array. 

  1. Count total digits in the number.
  2. Declare a char array of size digits in the number.
  3. Separating integer into digits and accommodate it to a character array.
  4. Add ASCII value of character ‘0’ is 48 in each element of the array.

Below is the implementation of the above approach:

C++




// C++ program to convert integer
// number into character array
 
#include <iostream>
#include <cstring>
using namespace std;
 
// Function to convert integer to
// character array
char* convertIntegerToChar(int N)
{
 
    // Count digits in number N
    int m = N;
    int digit = 0;
 
    while (m > 0) {
 
        // Increment number of digits
        digit++;
 
        // Truncate the last
        // digit from the number
        m /= 10;
    }
 
    // Declare char array for result
    char* arr = new char[digit];
 
    // Declare duplicate char array
    char arr1[digit + 1];
 
    // Separating integer
    // into digits and
    // accommodate it
    // to character array
    int index = 0;
 
    while (N > 0) {
        index++;
 
        // Separate last digit from
        // the number and add ASCII
        // value of character '0' is 48
        arr1[index] = static_cast<char>(N % 10 + 48);
 
        // Truncate the last
        // digit from the number
        N /= 10;
    }
 
    // Reverse the array for result
    for (int i = 0; i < index; i++) {
        arr[i] = arr1[index - i];
    }
 
    // Char array truncate by null
    arr[index] = '\0';
 
    // Return char array
    return arr;
}
 
// Driver Code
int main()
{
 
    // Given number
    int N = 12349;
    int len = 5;
 
    // Function call
    char* arr = convertIntegerToChar(N);
 
    // Print array
    for (int i = 0; i < len; i++)
        cout << arr[i] << " ";
 
    // Free the memory allocated
    delete[] arr;
 
    return 0;
}
 
// contributed by adityasha4x71


C




// C program to convert integer
// number into character array
 
#include <stdio.h>
#include <stdlib.h>
 
// Function to convert integer to
// character array
char* convertIntegerToChar(int N)
{
 
    // Count digits in number N
    int m = N;
    int digit = 0;
    while (m) {
 
        // Increment number of digits
        digit++;
 
        // Truncate the last
        // digit from the number
        m /= 10;
    }
 
    // Declare char array for result
    char* arr;
 
    // Declare duplicate char array
    char arr1[digit];
 
    // Memory allocation of array
    arr = (char*)malloc(digit);
 
    // Separating integer into digits and
    // accommodate it to character array
    int index = 0;
    while (N) {
 
        // Separate last digit from
        // the number and add ASCII
        // value of character '0' is 48
        arr1[++index] = N % 10 + '0';
 
        // Truncate the last
        // digit from the number
        N /= 10;
    }
 
    // Reverse the array for result
    int i;
    for (i = 0; i < index; i++) {
        arr[i] = arr1[index - i];
    }
 
    // Char array truncate by null
    arr[i] = '\0';
 
    // Return char array
    return (char*)arr;
}
 
// Driver Code
int main()
{
 
    // Given number
    int N = 12349;
    int len = 5;
 
    // Function call
    char* arr = convertIntegerToChar(N);
 
    // Print char array
    for (int i = 0; i < len; i++)
        printf("%c, ", arr[i]);
 
    return 0;
}


Java




// Java program to convert integer
// number into character array
class GFG{
     
// Function to convert integer to
// character array
static char[] convertIntegerToChar(int N)
{
 
    // Count digits in number N
    int m = N;
    int digit = 0;
     
    while (m > 0)
    {
         
        // Increment number of digits
        digit++;
 
        // Truncate the last
        // digit from the number
        m /= 10;
    }
 
    // Declare char array for result
    char[] arr;
 
    // Declare duplicate char array
    char []arr1 = new char[digit + 1];
 
    // Memory allocation of array
    arr = new char[digit];
 
    // Separating integer into digits and
    // accommodate it to character array
    int index = 0;
     
    while (N > 0)
    {
         
        // Separate last digit from
        // the number and add ASCII
        // value of character '0' is 48
        arr1[++index] = (char)(N % 10 + '0');
 
        // Truncate the last
        // digit from the number
        N /= 10;
    }
 
    // Reverse the array for result
    int i;
    for(i = 0; i < index; i++)
    {
        arr[i] = arr1[index - i];
    }
 
    // Return char array
    return (char[])arr;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given number
    int N = 12349;
    int len = 5;
 
    // Function call
    char[] arr = convertIntegerToChar(N);
 
    // Print char array
    for(int i = 0; i < len; i++)
        System.out.printf("%c, ", arr[i]);
}
}
 
// This code is contributed by amal kumar choubey


Python3




# Python3 program to convert integer
# number into character array
 
# Function to convert integer to
# character array
def convertIntegerToChar(N):
 
    # Count digits in number N
    m = N;
    digit = 0;
 
    while (m > 0):
 
        # Increment number of digits
        digit += 1;
 
        # Truncate the last
        # digit from the number
        m /= 10;   
 
    # Declare char array for result
    arr = ['0' for i in range(digit)]
 
    # Declare duplicate char array
    arr1 = ['0' for i in range(digit + 1)];
 
    # Separating integer
    # into digits and
    # accommodate it
    # to character array
    index = 0;
 
    while (N > 0):
        index += 1;
 
        # Separate last digit from
        # the number and add ASCII
        # value of character '0' is 48
        arr1[index] = chr(int(N % 10 + 48));       
 
        # Truncate the last
        # digit from the number
        N = N // 10;   
 
    # Reverse the array for result
    for i in range(0, index):
        arr[i] = arr1[index - i];   
 
    # Return char array
    return arr;
 
# Driver Code
if __name__ == '__main__':
 
    # Given number
    N = 12349;
    len = 5;
 
    # Function call
    arr = convertIntegerToChar(N);
 
    # Print array
    for i in range(0, len, 1):
        print(arr[i], end = " ");
 
# This code is contributed by gauravrajput1


C#




// C# program to convert integer
// number into character array
using System;
 
class GFG{
     
// Function to convert integer to
// character array
static char[] convertintToChar(int N)
{
 
    // Count digits in number N
    int m = N;
    int digit = 0;
     
    while (m > 0)
    {
         
        // Increment number of digits
        digit++;
 
        // Truncate the last
        // digit from the number
        m /= 10;
    }
 
    // Declare char array for result
    char[] arr;
 
    // Declare duplicate char array
    char []arr1 = new char[digit + 1];
 
    // Memory allocation of array
    arr = new char[digit];
 
    // Separating integer into digits and
    // accommodate it to character array
    int index = 0;
     
    while (N > 0)
    {
         
        // Separate last digit from
        // the number and add ASCII
        // value of character '0' is 48
        arr1[++index] = (char)(N % 10 + '0');
 
        // Truncate the last
        // digit from the number
        N /= 10;
    }
 
    // Reverse the array for result
    int i;
    for(i = 0; i < index; i++)
    {
        arr[i] = arr1[index - i];
    }
 
    // Return char array
    return (char[])arr;
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given number
    int N = 12349;
    int len = 5;
 
    // Function call
    char[] arr = convertintToChar(N);
 
    // Print char array
    for(int i = 0; i < len; i++)
        Console.Write("{0}, ", arr[i]);
}
}
 
// This code is contributed by amal kumar choubey


Javascript




<script>
    // Javascript program to convert integer
    // number into character array
     
    // Function to convert integer to
    // character array
    function convertIntegerToChar(N)
    {
 
        // Count digits in number N
        let m = N;
        let digit = 0;
 
        while (m > 0)
        {
 
            // Increment number of digits
            digit++;
 
            // Truncate the last
            // digit from the number
            m = parseInt(m / 10, 10);
        }
 
        // Declare char array for result
        let arr;
 
        // Declare duplicate char array
        let arr1 = new Array(digit + 1);
 
        // Memory allocation of array
        arr = new Array(digit);
 
        // Separating integer into digits and
        // accommodate it to character array
        let index = 0;
 
        while (N > 0)
        {
 
            // Separate last digit from
            // the number and add ASCII
            // value of character '0' is 48
            arr1[++index] = String.fromCharCode(N % 10 + '0'.charCodeAt());
 
            // Truncate the last
            // digit from the number
            N = parseInt(N / 10, 10);
        }
 
        // Reverse the array for result
        let i;
        for(i = 0; i < index; i++)
        {
            arr[i] = arr1[index - i];
        }
 
        // Return char array
        return arr;
    }
     
    // Given number
    let N = 12349;
    let len = 5;
  
    // Function call
    let arr = convertIntegerToChar(N);
  
    // Print char array
    for(let i = 0; i < len; i++)
        document.write(arr[i] + ", ");
 
// This code is contributed by divyeshtsbsdiya07
</script>


Output

1, 2, 3, 4, 9, 



Time Complexity: O(log N), where N is the input integer.
Space Complexity: O(digit), where the digit is the number of digits in the input integer.

Approach 2: We can further simplify above approach using dynamic array (vector in C++, ArrayList in Java and so on…). We will create a dynamic array and insert new digit at the beginning of this array so we will not have to calculate size of it separately and also we will not have to reverse the array. See the below implementation. 

C++




// C++ program to convert integer
// number into character array
 
#include <cstring>
#include <iostream>
#include <vector>
using namespace std;
 
vector<char> convertIntegerToChar(int N)
{
 
    vector<char> arr;
 
    while (N != 0) {
        // insert the digit to begining
        arr.insert(arr.begin(), N % 10 + '0');
        N /= 10;
    }
    return arr;
}
// Driver Code
int main()
{
    // Given number
    int N = 12349;
 
    // Function call
    vector<char> arr = convertIntegerToChar(N);
 
    // Print array
    for (auto& it : arr)
        cout << it << ", ";
 
    return 0;
}
 
// code and idea by Harsh Singh (hsnooob)


Java




import java.util.ArrayList;
import java.util.List;
 
public class IntegerToCharArray {
 
    // Function to convert an integer to a character array
    public static List<Character> convertIntegerToChar(int N) {
        List<Character> arr = new ArrayList<>();
 
        while (N != 0) {
            // Insert the digit at the beginning of the list
            arr.add(0, (char) (N % 10 + '0'));
            N /= 10;
        }
        return arr;
    }
 
    public static void main(String[] args) {
        // Given number
        int N = 12349;
 
        // Function call
        List<Character> arr = convertIntegerToChar(N);
 
        // Print the character array
        for (char ch : arr) {
            System.out.print(ch + ", ");
        }
    }
}


Python3




# Function to convert integer to character array
def convertIntegerToChar(N):
    arr = []
 
    while N != 0:
        # insert the digit to beginning
        arr.insert(0, chr((N % 10) + ord('0')))
        N //= 10
    return arr
 
 
# Driver Code
if __name__ == '__main__':
    # Given number
    N = 12349
 
    # Function call
    arr = convertIntegerToChar(N)
 
    # Print array
    for ch in arr:
        print(ch, end=', ')


C#




using System;
using System.Collections.Generic;
 
public class Program {
    public static List<char> ConvertIntegerToChar(int N)
    {
        List<char> arr = new List<char>();
 
        while (N != 0) {
            // insert the digit to beginning
            arr.Insert(0, (char)(N % 10 + '0'));
            N /= 10;
        }
 
        return arr;
    }
 
    public static void Main()
    {
        // Given number
        int N = 12349;
 
        // Function call
        List<char> arr = ConvertIntegerToChar(N);
 
        // Print array
        foreach(char c in arr) { Console.Write(c + ", "); }
    }
}


Javascript




// JavaScript program to convert integer
// number into character array
function convertIntegerToChar(N)
{
 
    let arr = [];
     
    while (N !== 0)
    {
     
        // insert the digit to begining
        arr.unshift(String.fromCharCode(N % 10 + '0'.charCodeAt()));
        N = Math.floor(N / 10);
    }
    return arr;
}
 
// Driver Code
let N = 12349;
 
// Function call
let arr = convertIntegerToChar(N);
 
// Print array
for (let i = 0; i < arr.length; i++) {
    process.stdout.write(arr[i] + ', ');
}


Output

1, 2, 3, 4, 9, 



Time Complexity: O(log N), where N is the input integer.
Space Complexity: O(digit), where the digit is the number of digits in the input integer.

Approach 3: We can also convert the given number to string and then put each character in the vector.

C++




// C++ program to convert integer
// number into character array
 
#include <cstring>
#include <iostream>
using namespace std;
 
// Function to convert integer to
// character array
char* convertIntegerToChar(int N)
{
    // convert the number to string
    string temp = to_string(N);
 
    // get the digits
    int digit = temp.size();
 
    // Declare char array
    char* arr = new char[digit];
 
    // copy string elements to the array
    int index = 0;
    for (auto& it : temp) {
        arr[index++] = it;
    }
    // Char array truncate by null
    arr[index] = '\0';
 
    // Return char array
    return arr;
}
 
// Driver Code
int main()
{
 
    // Given number
    int N = 12349;
    int len = 5;
 
    // Function call
    char* arr = convertIntegerToChar(N);
 
    // Print array
    for (int i = 0; i < len; i++)
        cout << arr[i] << ", ";
 
    // Free the memory allocated
    delete[] arr;
 
    return 0;
}
 
// code and idea by HARSH SINGH (hsnooob)


Java




import java.util.*;
 
public class Main
{
 
  // Function to convert integer to character array
  public static char[] convertIntegerToChar(int N)
  {
 
    // Convert the number to string
    String temp = Integer.toString(N);
 
    // Get the length of the string
    int len = temp.length();
 
    // Declare char array
    char[] arr = new char[len];
 
    // Copy string elements to the array
    for (int i = 0; i < len; i++) {
      arr[i] = temp.charAt(i);
    }
 
    // Return char array
    return arr;
  }
 
  // Driver code
  public static void main(String[] args) {
    // Given number
    int N = 12349;
    int len = 5;
 
    // Function call
    char[] arr = convertIntegerToChar(N);
 
    // Print array
    for (int i = 0; i < len; i++) {
      System.out.print(arr[i] + ", ");
    }
 
    // Free the memory allocated
    arr = null;
  }
}


Python3




# Python code of the above approach
def convert_int_to_char(n):
    # converting the passed
    # integer to string
    temp = str(n)
     
    # finding the length
    # of the converted string
    length = len(temp)
     
    # Initializing a new
    # blank array
    arr = []
     
    # Iterating till the length
    # of the string
    for i in range(length):
        arr.append(temp[i])
     
    # Returing the resultant array
    return arr
 
# Driver Code
a = 12349
 
# Calling the function by passing
# the number as argument and storing the
# result in the variable
res = convert_int_to_char(a)
 
# Printing each element from the variable
# seperated by comma
for i in res:
    print(i,end=",")
 
# This Code is Contributed by Dwaipayan Bandyopadhyay


C#




using System;
 
class Program
{
    // Function to convert integer to character array
    static char[] ConvertIntegerToChar(int N)
    {
        // Convert the number to string
        string temp = N.ToString();
 
        // Get the digits
        int digit = temp.Length;
 
        // Declare char array
        char[] arr = new char[digit + 1];
 
        // Copy string elements to the array
        for (int i = 0; i < digit; i++)
        {
            arr[i] = temp[i];
        }
 
        // Char array truncate by null
        arr[digit] = '\0';
 
        // Return char array
        return arr;
    }
 
    // Driver code
    static void Main()
    {
        // Given number
        int N = 12349;
        int len = 5;
 
        // Function call
        char[] arr = ConvertIntegerToChar(N);
 
        // Print array
        for (int i = 0; i < len; i++)
        {
            Console.Write(arr[i] + ", ");
        }
        Console.WriteLine();
 
        // Free the memory allocated
        Array.Clear(arr, 0, arr.Length);
 
        Console.ReadLine();
    }
}


Javascript




// Function to convert integer to character array
function convertIntegerToChar(N) {
    // Convert the number to a string
    let temp = N.toString();
 
    // Get the digits
    let digit = temp.length;
 
    // Declare an array to store characters
    let arr = new Array(digit);
 
    // Copy string elements to the array
    for (let index = 0; index < digit; index++) {
        arr[index] = temp.charAt(index);
    }
 
    // Return the character array
    return arr;
}
 
// Driver Code
let N = 12349;
let len = 5;
 
// Function call
let arr = convertIntegerToChar(N);
 
// Print array with comma separator
console.log(arr.join(', '));


Output

1, 2, 3, 4, 9, 



Time Complexity: O(log N), where N is the input integer.
Space Complexity: O(digit), where the digit is the number of digits in the input integer.



Last Updated : 17 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads