给定一个包含数字4的整数N至少一次。任务是将数字分成两部分x1和x2 ,使得:
- x1 + x2 = N 。
- 并且没有任何部分包含数字4 。
请注意,可能有多个答案。
例子:
Input: N = 4
Output: 1 3
1 + 3 = 4
Input: N = 9441
Output: 9331 110
9331 + 110 = 9441
方法:由于数字可能太大,将数字作为字符串。把它分成两个字符串:
- 对于字符串1,找到它的字符串更改为3数字4的所有位置,我们也可以将其更改为另一个号码。
- 对于第二个字符串,在数字 4 的所有位置放置 1,在从数字 4 的第一个位置到字符串末尾的所有剩余位置放置 0。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to print the two parts
void twoParts(string str)
{
int flag = 0;
string a = "";
// Find the position of 4
for (int i = 0; i < str.length(); i++) {
if (str[i] == '4') {
str[i] = '3';
a += '1';
flag = 1;
}
// If current character is not '4'
// but appears after the first
// occurrence of '4'
else if (flag)
a += '0';
}
// Print both the parts
cout << str << " " << a;
}
// Driver code
int main()
{
string str = "9441";
twoParts(str);
return 0;
}
Java
// Java implementation of the approach
class GfG
{
// Function to print the two parts
static void twoParts(String str)
{
int flag = 0;
String a = "";
char[] gfg = str.toCharArray();
// Find the position of 4
for (int i = 0; i < str.length(); i++)
{
if (gfg[i] == '4')
{
gfg[i] = '3';
a += '1';
flag = 1;
}
// If current character is not '4'
// but appears after the first
// occurrence of '4'
else if (flag != 0)
a += '0';
}
str = new String(gfg);
// Print both the parts
System.out.print(str + " " + a);
}
// Driver code
public static void main(String []args)
{
String str = "9441";
twoParts(str);
}
}
// This code is contributed by Rituraj Jain
Python3
# Python3 implementation of the approach
# Function to print the two parts
def twoParts(string) :
flag = 0;
a = "";
# Find the position of 4
for i in range(len(string)) :
if (string[i] == '4') :
string[i] = '3';
a += '1';
flag = 1;
# If current character is not '4'
# but appears after the first
# occurrence of '4'
elif (flag) :
a += '0';
string = "".join(string);
# Print both the parts
print(string, a);
# Driver code
if __name__ == "__main__" :
string = "9441";
twoParts(list(string));
# This code is contributed by Ryuga
C#
// C# implementation of the approach
using System;
class GfG
{
// Function to print the two parts
static void twoParts(string str)
{
int flag = 0;
string a = "";
char[] gfg = str.ToCharArray();
// Find the position of 4
for (int i = 0; i < str.Length; i++)
{
if (gfg[i] == '4')
{
gfg[i] = '3';
a += '1';
flag = 1;
}
// If current character is not '4'
// but appears after the first
// occurrence of '4'
else if (flag != 0)
a += '0';
}
str = new String(gfg);
// Print both the parts
Console.WriteLine(str + " " + a);
}
// Driver code
static void Main()
{
string str = "9441";
twoParts(str);
}
}
// This code is contributed by mits
PHP
Javascript
输出:
9331 110
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。