How to concatenate two Integer values into one?
Given two integers n1 and n2, the task is to concatenate these two integers into one integer.
Example:
Input: n1 = 12, n2 = 34
Output: 1234
Input: n1 = 1, n2 = 93
Output: 193
Approach: The simplest approach to do this is:
- Convert both numbers to string
- Concatenate both strings into one, as this is comparatively easy
- Convert this concatenated string back to integer
Program:
C++
#include <iostream>
#include <string>
using namespace std;
int concat( int a, int b)
{
string s1 = to_string(a);
string s2 = to_string(b);
string s = s1 + s2;
int c = stoi(s);
return c;
}
int main()
{
int a = 23;
int b = 43;
cout << concat(a, b) << endl;
return 0;
}
|
C
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int concat( int a, int b)
{
char s1[20];
char s2[20];
sprintf (s1, "%d" , a);
sprintf (s2, "%d" , b);
strcat (s1, s2);
int c = atoi (s1);
return c;
}
int main()
{
int a = 23;
int b = 43;
printf ( "%d\n" , concat(a, b));
return 0;
}
|
Java
public class GFG {
static int concat( int a, int b)
{
String s1 = Integer.toString(a);
String s2 = Integer.toString(b);
String s = s1 + s2;
int c = Integer.parseInt(s);
return c;
}
public static void main(String args[])
{
int a = 23 ;
int b = 43 ;
System.out.println(concat(a, b));
}
}
|
Python3
def concat(a, b):
s1 = str (a)
s2 = str (b)
s = s1 + s2
c = int (s)
return c
a = 23
b = 43
print (concat(a, b))
|
C#
using System;
class GFG
{
static int concat( int a, int b)
{
String s1 = a.ToString();
String s2 = b.ToString();
String s = s1 + s2;
int c = int .Parse(s);
return c;
}
public static void Main(String []args)
{
int a = 23;
int b = 43;
Console.WriteLine(concat(a, b));
}
}
|
Javascript
<script>
function concat(a , b) {
var s1 = a.toString();
var s2 = b.toString();
var s = s1 + s2;
var c = parseInt(s);
return c;
}
var a = 23;
var b = 43;
document.write(concat(a, b));
</script>
|
Output:
2343
Time Complexity: O(d1+d2) where d1=log10(a) and d2=log10(b)
Auxiliary Space: O(d1+d2)
Last Updated :
13 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...