+ 1

Insert a number in the middle

Requirement Read from the keyboard two natural numbers A and B. Insert the number B in the middle of the number A. For example if we read A = 1234 and B = 77 then the result obtained will be N = 127734. Input data On the first line will be the natural numbers A and B. Output data The result obtained after insertion will be displayed. Restrictions and specifications 0 <A, B <1,000,000 It is guaranteed that A has an even number of digits. Example Input data Output data 123456 9 1239456 1234 77 127734 I tried the next solution but I got stuck: https://onlinegdb.com/BkrZ-XiLd

19th Apr 2021, 3:26 PM
Florin H
Florin H - avatar
5 Réponses
+ 3
No need to use math operations. Just read both numbers as strings, then calculate the middle of the first string, then use the std::string::insert() method to insert the second string in the mid-position of the first one. std::string::insert(): http://www.cplusplus.com/reference/string/string/insert/ https://en.cppreference.com/w/cpp/string/basic_string/insert
19th Apr 2021, 4:33 PM
XXX
XXX - avatar
+ 1
thanks. I wanted a variant without insert. I'm at the beginning. I try to lay the foundations for my programming and it would have helped me more to understand the process behind it.
19th Apr 2021, 5:08 PM
Florin H
Florin H - avatar
+ 1
Florin H When you think about it, inserting a number into the middle of another is an operation more suited for strings right? Because you're not actually doing any operation on the number, you are changing how the number looks like in text form. So I think std::string::insert() should be the correct way to do it. Atleast that's what I feel. Anyways, it's bedtime for me now. I'll try to see tomorrow if I can find the mistake in your code. It doesn't look very easy to do it using arithmetic operations.
19th Apr 2021, 7:43 PM
XXX
XXX - avatar
0
If you have these two numbers as strings, you can use for loop to combine them like that: for(auto& x :str1) { if(x==str1[str1.size()/2]) { new_string+=str2; } new_string+=x; } Where: str1="1234"; str2="77"; new_string(""); // empty string It's not the best solution, and it can be done better, but that's my first thought of doing it manually
19th Apr 2021, 5:22 PM
Michal Doruch