c++ changing number digits places? - c++

I have a 3 digit number, let's say n = 135. I need to change the digits in the number so that I get a different number. Putting first number in the middle for the result of 315. I figured first thing i have to do is extract separate digits and I went with this
int n = 135;
int a, b, c, x;
a = n / 100;
b = n % 100 / 10;
c = n % 10;
Now I have separate digit values but no idea how to put them all together into one variable to get x = 315.
EDIT:
Figured it out after writing. Don't know how to mark post as solved without choosing an answer. Solved it like this (if someone else encounters same problem):
x = b * 10 + a;
x = x * 10 + c;
cout << "Changed number: " << x << endl;

Multiplication is your friend.
x = b * 100 + a * 10 + c;

So, alright. The way I would do this, and please correct me if this doesn't work, would be to make it into a string, and then re-arrange stuff like that. To do that, we could use the string formatting library like this:
string number = to_string(135);
Then, you could do stuff like this:
char swap;
swap = number[0];
number[0] = number[1];
number[1] = swap;
That'll swap the first and second items, making it 315. The others follow logically. After you're done, just convert the string back to an int, like this:
int number = atoi(number.c_str());

Related

if statement inside of for loop not being executed

Writing a program to solve problem four of project euler: Find the largest palindrome made from the product of two 2-digit numbers. Heres my reprex:
#include <iostream>
int reverseNumber(int testNum)
{
int reversedNum, remainder = 0;
int temp = testNum;
while(temp != 0)
{
remainder = temp % 10;
reversedNum = reversedNum * 10 + remainder;
temp /= 10;
}
return reversedNum;
}
int main()
{
const int MIN = 100;
int numOne = 99;
int product = 0;
for(int numTwo = 10; numTwo < 100; numTwo++)
{
product = numOne * numTwo;
if (reverseNumber(product) == product)
{
int solution = product;
std::cout << solution << '\n';
return 0;
}
}
return 0;
}
My main thought process behind this is that the for loop will go through every number from 10 to 99 and multiply it by 99. My intended outcome is for it to print 9009 which is the largest palindrome with 2 factors of 2 digits. So what I think should happen here is the for loop will go from 10 to 99, and each loop it should go through the parameters of the if statement which reverses the number and sees if it equals itself.
I've made sure it wasn't a compiler issue, as this is recurring between different compilers. The reverseNumber() function returns the proper number every time I've tested it, so that shouldn't be the problem, however this problem only occurs when the function is involved in the logical comparison. By this I mean if that even I set it equal to a variable and put the variable in the if parameters, the issue still occurs. I'm pretty much stumped. I just hope it's not some silly mistake as I've been on this for a couple days now.
int reversedNum, remainder = 0;
You should be aware that this gives you (in an automatic variable context) a zero remainder but an arbitrary reversedNum. This is actually one of the reasons some development shops have the "one variable per declaration" rule.
In other words, it should probably be:
int reversedNum = 0, remainder;
or even:
int reversedNum = 0;
int remainder;
One other thing that often helps out is to limit the scope of variable to as small an area as possible, only bringing them into existence when needed. An example of that would be:
int reverseNumber(int testNum) {
int reversedNum = 0;
while (testNum != 0) {
int remainder = testNum % 10;
reversedNum = reversedNum * 10 + remainder;
testNum /= 10;
}
return reversedNum;
}
In fact, I'd probably go further and eliminate remainder altogether since you only use it once:
reversedNum = reversedNum * 10 + testNum % 10;
You'll notice I've gotten rid of temp there as well. There's little to gain by putting testNum into a temporary variable since it's already a copy of the original (as it was passed in by value).
And one other note, more to do with the problem rather than the code. You seem to be assuming that there is a palindrome formed that is a multiple of 99. That may be the case but a cautious programmer wouldn't rely on it - if you're allowed to assume things like that, you could just replace your entire program with:
print 9009
Hence you should probably check all possibilities.
You also get the first one you find which is not necessarily the highest one (for example, let's assume that 99 * 17 and 99 * 29 are both palindromic - you don't want the first one.
And, since you're checking all possibilities, you probably don't want to stop at the first one, even if the nested loops are decrementing instead of incrementing. That's because, if 99 * 3 and 97 * 97 are both palindromic, you want the highest, not the first.
So a better approach may be to start high and do an exhaustive search, while also ensuring you ignore the palindrome check of candidates that are smaller that your current maximum, something like (pseudo-code)
# Current highest palindrome.
high = -1
# Check in reverse order, to quickly get a relatively high one.
for num1 in 99 .. 0 inclusive:
# Only need to check num2 values <= num1: if there was a
# better palindrome at (num2 * num1), we would have
# already found in with (num1 * num2).
for num2 in num1 .. 0 inclusive:
mult = num1 * num2
# Don't waste time doing palindrome check if it's
# not greater than current maximum - we can't use
# it then anyway. Also, if we find one, it's the
# highest possible for THIS num1 value (since num2
# is decreasing), so we can exit the num2 loop
# right away.
if mult > high:
if mult == reversed(mult):
high = mult
break
if high >= 0:
print "Solution is ", high
else:
print "No solution"
In addition to properly initializing your variables, if you want the largest palindrome, you should switch the direction of your for loop -- like:
for(int numTwo = 100; numTwo > 10; numTwo--) {
...
}
or else you are just printing the first palindrome within your specified range

Why does the following program gives wrong answer when I remove "+ mod" from statement check . Problem link: https://www.codechef.com/problems/FFC219B

The statement check is where I don't understand why it shows wrong answer on submission when I write "sum = (solution[R]-solution[L-1])%mod;" instead. Here I have not added mod within the bracket. I don't see how the answer changes by adding a value of taking the mod of same. Problem code in codechef: https://www.codechef.com/problems/FFC219B
#include<iostream>
#define ll long long
#define mod 1000000007 //the modulus we need to take for the final answer
#define endl "\n"
using namespace std;
long long solution[100007] = {0}; //Initialising all the values with zero
int main(){
ios_base :: sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
solution[0] = 0;
ll a1=1,a2=2,a3=3,a4=4; //The variable initialising as per the problem
for(int i = 1;i <= 100007;i++){
ll k=(a1 * a2) % mod * a3 % mod * a4 % mod;
solution[i] = (solution[i-1]+k)%mod; //Adding the previous values as we are to find the sum in range
a1++;
a2++;
a3++;
a4++;
}
int t; //Taking input for number of test cases
cin>>t;
while(t-->0)
{
int L,R;
cin>>L>>R; //Taking the range input
long long sum = 0;
sum = (solution[R]-solution[L-1] + mod)%mod; //statement check & final answer
cout<<sum<<endl;
}
return 0;
}
The program can give the incorrect answer since the correct answer must always be a positive - not a negative - number.
When you subtract consecutive modulo values, the result may well be negative even though the numbers themselves are increasing (eg, (4^3)%10 - (4^2)%10 = 64%10 - 16%10 = 4-6 = -2), . This means “solution[R]-solution[L-1]” may also well be negative, which means “(solution[R]-solution[L-1]) % mod” will also be negative - although clearly the answer (the number of people affected) must always be positive.
So adding the mod value in this fashion ensures that the result will always be positive.

How to start on this C interview code test?

I got a really interesting question at a company, and I can't seem to find an answer at all.
#include <cstdio>
int main()
{
int num = 123456789;
int res = 0;
for (int i = 0; i<111111111; i++)
{
res=(res+num)%1000000000;
}
printf("06 %09d", res);
return 0;
}
I should declare num so the output is my mobile number, 305089171.
Any idea how to do that?
So to solve the problem we begin with units digit.
We need 1 at units digit so make num = 1.
Now we have res as 111111111.
Now we need 7 at tens digits. So we make num = (7 - 1(tens digit in step 2)) 1 = 61. (Also note that multiplying digit at tens place will only affect digts to left of it).
Now we have res as 777777771.
Now we need 1 at hundreds place. So if we make num = 461 (since 7+4 = 1)
and so on.
The mathematical reasoning I could think of is when you multiply a number by 111111111, digits at say tens place will only affect digits to left of it and not the digits to right of it.
Here is the value you need to put in num:
254197461
I got it by adding additional numbers one by one to num, i let you check what happens yourself.
I have no mathemacital explaination to that, but try putting numbers one by one into num and you may understand:.
1 / 61 / 461 / 7461...

How do I get the number of a specific place in an int in C++?

So I have an int that counts upwards.
Let's say we're up to 65,000 already.
I need to get the number in the thousandth place (the 5), to be assigned to another int.
I found the following snippet which is pretty easy but not quite what I need.
You can use % operator for any number of integers you want to
separate. For example 888881%10 will give you 1 and 888881%100 will
give you 81...
Thanks!
You probably need this.
int AtPos(int number, int pos)
{
return ((number > 0 ? number : -number) / (int)pow(10, pos)) % 10;
}
If this is that you are looking for, arguments validity check should be added.
EDIT.
I just noticed, you need to assign different number in specified position. So you need this improvement:
int& SetValueAtPos(int& number, int pos, int newValue)
{
int power = (int)pow(10, pos);
number -= AtPos(number, pos) * power;
number += power * newValue;
return number;
}
Additionally you can merge those functions and cache value of pow(10, pos) so it would be more optimal.
Try something like this
int a =65432;
int b = ((a%10000)-(a%1000))/1000;
here (a%10000) = 5432
and (a%1000) = 432
so (a%10000)-(a%1000) will be 5000
and finally 5000/1000 = 5
or directly you can use
int b = (a%10000)/1000;
What #Matt suggested in comment is:
int num1 = 65000;
int num2 = num%10000; //num2 is 5000
num2 = num2/1000;
Output: 5

Test if numbers are divisible by 4, up to 100 digits

Simply enough, I practice programming via an online judge. This is a rather stupid problem, really easy. However, The judge keeps saying I have a wrong answer. I'm just going to paste the code which is just a few lines, and a link to the problem.
#include <iostream>
#include <string>
using namespace std;
int main() {
int cases = 0;
string solution = "";
cin >> cases;
if (cases > 100)
return(0);
for (int i = 0; i < cases; i++) {
int temp = 0;
cin >> temp;
if ((temp % 4) == 0)
solution +="Y";
else
solution +="N";
}
for (int j = 0; j < cases; j++) {
if (solution[j] == 'Y')
cout << "YES";
else
cout << "NO";
cout << endl;
}
}
The problem is simply to output YES or NO for each number that is input that is divisible by 4, YES for if it is, NO if its not. The problem and every minute detail can be found: http://coj.uci.cu/24h/problem.xhtml?abb=1306
This is rather silly, but I'm going bonkers here trying to figure out what I'm doing WRONG!
A number is divisible by 4 if its two last decimal digits are divisible by 4.
The end.
P.S. Sometimes it makes sense to stop thinking as a programmer and remember algebra/arithmetics.
As I said in a comment, the problem is that you cannot read a 100 digit number into an int directly. I don't want to give you the solution to the algorithm, but a hint that should help: How many digits would you need to know if the number was divisible by 2 or by 5? And how could you extend that to 4?
If you express a number X as Y + d where d = X%100 and Y = X -d we can see that Y will always be divisible by 100, for example for the number X = 343535, Y would be 343500 and d would be 35. Since Y is divisible by 100, implies that is divisible by 4, so you can determinate if X is divisible by 4, checking if d is divisible by 4, i.e the last two digits of X.
Formally it would be:
Y = 4*Z
Y = 100*X +d
Y = 4*Z = 4*25*X +d
d = 4*(Z - 25*X)
i.e if Y is multiple of 4, d is multiple of 4
You have to apply this principle to solve your problem.
Simply read a raw string and check if the number represented by the last two characters are divisible by four.
As tempting as might be, you don't need a BitInteger to figure out whether a 100 digit number, of 1 million digit number is divisible by 4. That's just simple math, that you should be able to figure by yourself in a minute, if you don't know the rule.
Perhaps the problem is this if (cases > 100). because of this -1 would be a valid option.
Change to if (cases > 100 && cases < 1) to fix it
I wouldn't even read the whole number. I would just read the last 2 digits before the EOF char (end of file).
string inputString;
while(getline(cin,inputString)
{
//code for finding x %4==0 and output
}
then all you need to do is convert the last 2 chars into a int and then do your mod 4 code. (you'll need a catch value for numbers < 10, but that shouldn't be hard)