Find the conjugate of a Complex number
Given a complex number str in the form of a string, the task is to determine the conjugate of this complex number.
Examples:
Input: str = "3 - 4i"
Output: 3 + 4i
Input: str = "6 - 5i"
Output: 6 + 5i
Approach: A complex number is said to be a conjugate of another complex number if only the sign of the imaginary part of the two numbers is different.
If complex number = x + iy
Conjugate of this complex number = x - iy
Below is the implementation of the above approach :
C++
#include <bits/stdc++.h>
using namespace std;
void solve(string s)
{
string z = s;
int l = s.length();
int i;
if (s.find( '+' ) < l) {
i = s.find( '+' );
replace(s.begin(),
s.end(),
'+' , '-' );
}
else {
i = s.find( '-' );
replace(s.begin(),
s.end(),
'-' , '+' );
}
cout << "Conjugate of "
<< z << " = "
<< s << endl;
}
int main()
{
string s = "3-4i" ;
solve(s);
return 0;
}
|
Java
class GFG
{
static void solve(String s)
{
String z = s;
int l = s.length();
int i;
String str;
if (s.indexOf( '+' ) != - 1 ) {
i = s.indexOf( '+' );
str = s.replace( '+' , '-' );
}
else {
i = s.indexOf( '-' );
str = s.replace( '-' , '+' );
}
System.out.println( "Conjugate of "
+ z + " = "
+ str);
}
public static void main(String []args)
{
String s = "3-4i" ;
solve(s);
}
}
|
Python3
def solve(s):
z = s
l = len (s)
i = 0
if (s.find( '+' ) ! = - 1 ):
i = s.find( '+' )
s = s.replace( '+' , '-' )
else :
i = s.find( '-' )
s = s.replace( '-' , '+' , 1 )
print ( "Conjugate of " ,z, " = " ,s)
s = "3-4i"
solve(s)
|
C#
using System;
class GFG{
static void solve(String s)
{
String z = s;
int l = s.Length;
int i;
String str;
if (s.IndexOf( '+' ) != -1)
{
i = s.IndexOf( '+' );
str = s.Replace( '+' , '-' );
}
else
{
i = s.IndexOf( '-' );
str = s.Replace( '-' , '+' );
}
Console.WriteLine( "Conjugate of " + z +
" = " + str);
}
public static void Main(String []args)
{
String s = "3-4i" ;
solve(s);
}
}
|
Javascript
<script>
function solve(s)
{
let z = s;
var l = s.length;
var i;
if (s.indexOf( '+' ) != -1) {
i = s.indexOf( '+' );
s = s.replace( '+' , '-' );
}
else {
i = s.indexOf( '-' );
s = s.replace( '-' , '+' );
}
document.write( "Conjugate of " +z+ " = " +s+ "<br>" );
}
let s = "3-4i" ;
solve(s);
</script>
|
Output:
Conjugate of 3-4i = 3+4i
Time Complexity: O(|s|)
Auxiliary Space: O(1)
Last Updated :
21 Nov, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...