How to split up a two-digit number in C - c

Let's say I have a number like 21 and I want to split it up so that I get the numbers 2 and 1.
To get 1, I could do 1 mod 10. So basically, the last digit can be found out by using mod 10.
To get 2, I could do (21 - (1 mod 10))/10.
The above techniques will work with any 2-digit number.
However, let me add a further constraint, that mod can only be used with powers of 2. Then the above method can't be used.
What can be done then?

2 == 23 / 10
3 == 23 - (23 / 10) * 10

To get 2 you can just do
int x = 23 / 10;
remember that integer division drops the fractional portion (as it can't be represented in an integer).
Modulus division (and regular division) can be used for any power, not just powers of two. Also a power of two is not the same thing as a two digit number.
To split up a three digit number
int first = 234/100;
int second = (234/10)-first*10;
int third = (234/1)-first*100-second*10;
with a little work, it could also look like
int processed = 0;
int first = 234/100-processed;
processed = processed + first;
processed = processed * 10;
int second = 234/10-processed;
processed = processed + second;
processed = processed * 10;
... and so on ...
If you put a little more into it, you can write it up as a loop quite easily.

what about
x%10 for the second digit and
x/10 for the first?

Related

Modify Nth Digit

Given a number, I want to modify the Nth digit of the number.
For example, given 1237645, I want to change the 4th digit from the right, which is 7 in this case, to say 5.
The only way in which I can think of is to do this
N = 1237645
fourthDigit = (N / 1000) % 10
N -= fourthDigit * 1000 // make fourth digit 0
N += 5 * 1000 // make fourth digit 5
But this is quite inefficient. Is there a better way to this? I cannot use array to represent N due to memory constraints.
You can do it in one arithmetic operation:
N = 1237645
fourthDigit = (N / 1000) % 10
N -= (fourthDigit-5) * 1000
provided fourthDigit >= 5, otherwise the last line becomes
N += (newDigit-fourthDigit)*1000
Is this embedded system programming?
If it is, then try storing numbers as binary-coded decimal (BCD), then convert to binary if you need to. It is probably easier to convert from BCD to binary than the other way around.
Also see: http://homepage.divms.uiowa.edu/~jones/bcd/bcd.html
BTW, right here in the room with me is a clock which keeps time in BCD. This way, it doesn't have to divide by 10 for display.

How to rotate n-digits of a number without arrays?

The problem: user inputs two numbers: a big one, and a small one.
The small number is the number of digits from the last digit that will transfer into the front, and the remaining numbers will follow.
For example: if the big number is 456789 and the small one is 3, the result will be: 789456.
my idea was as follows:
if(...) {
newNum = BigNumber%(10*SmallNumber);
printf("%d", remainder");
SmallNumber--;
}
but it doesn't print in the order I was hoping for, digit by digit, and I can't understand why.
If using arrays would be allowed, it was no problem. Also I'm not allowed to use string.length, which also make it lots easier.
Rotating a number can be performed as a combination of cuts, shifts, and additions. For example, if you have a number 123456789 and you need to rotate it by 3, you can do it as follows:
Cut off the last three digits 123456789
Shift the remaining number by three digits to make 123456789
Shift the last three digits by six to make 789000000
Add the two numbers together 789000000 + 123456 to get the result 789123456.
Here is how you do these operations on decimal numbers:
Cutting off the last k digits is done with modulo % 10k
Shifting right by k digits is equivalent to integer division by 10k
Shifting left by k digits is equivalent to multiplication by 10k
Figuring out the number of significant digits in a number can be done by repeated integer division by ten.
Addition is done the usual way.
I think below code would help you -
//Here size = number of digits in bignumber-1
while(smallnumber--) {
temp = (bignumber - bignumber%pow(10,size))/(pow(10,size);
bignumber = bignumber%pow(10,size);
bignumber = bignumber*10 + temp;
}
Try this version:
#include <stdio.h>
#include <math.h>
int main(void)
{
long int num = 34234239;
int swap = 5, other;
long int rem = num % (int)(pow(10,swap)); /*The part that is shifted*/
other = log10(num-rem)+1-swap; /*Length of the other part*/
/* Result = (part to shift)*(Other part's length) + (Other part)*(Shifts) */
num = rem*(int)pow(10,other) + (num-rem)/(int)pow(10,swap);
printf("%ld\n",num);
return 0;
}

How do I populate an array with the digits of a given integer in C? [duplicate]

This question already has answers here:
convert an integer number into an array
(8 answers)
Closed 7 years ago.
So lets say you have an integer in your code declared
int my_num = 967892;
and you have an array
int a[6];
How would you put that integer into the array so it looks like this?
{ 9, 6, 7, 8, 9, 2 }
Perhaps like this:
const unsigned char digits[] = { 9, 6, 7, 8, 9, 2 };
but there are many things that are unclear with your question, of course.
If you want to do this at runtime, as your comment now makes me believe, you need more code of course. Also, it will be tricky to make the array "fit" the number exactly, since that requires runtime-sizing of the array.
The core operation is % 10, which when applied to a number results in the rightmost digit (the "ones" digit).
You can do this by getting each digit and putting it into an array. Kudos to #unwind for thinking of using unsigned int because digits don't have signs. I didn't think of that.
DISClAIMER: this code is untested but would, theoretically, if I haven't made any mistakes that the community will catch, accomplish your task.
NOTE: This program is implementation-defined when theNum is negative. See this SO question for more info on what that means. Also, the accepted answer in the question of which this post is a duplicate has shorter code than this but uses log10 which (according to commenters) could be inaccurate.
//given theNum as the number
int tmp = theNum;
int magnitude = 0;
//if you keep dividing by 10, you will eventually reach 0 (integer division)
//and that will be the magnitude of the number + 1 (x * 10^n-1)
for (; tmp > 0; magnitude++){ //you could use a while loop but this is more compact
tmp /= 10;
}
//the number of digits is equal to the magnitude + 1 and they have no sign
unsigned int digits[magnitude];
//go backwards from the magnitude to 0 taking digits as you go
for (int i = magnitude - 1; i > 0; i--){
//get the last digit (because modular arithmetic gives the remainder)
int digit = theNum % 10;
digits[i] = digit; //record digit
theNum /= 10; //remove last digit
}
If this shall be done dynamically:
Determine the number of digits as N.
Allocate an array large enough (>=N) to hold the digits.
Loop N times chopping of the digits and storing them in the array allocated under 2.
The least significant digit is num % 10
The next digit can be found by num/=10;
This works for positive numbers, but is implementation defined for negative
I assume you want to achieve something like this:
int arr[SOME_SIZE];
int len = int_to_array(arr,421);
assert(len == 3);
assert(arr[0] == 4);
assert(arr[1] == 2);
assert(arr[1] == 1);
Since this is probably a homework problem, I won't give the full answer, but you'll want a loop, and you'll want a way to get the last decimal digit from an int, and an int with the last digit removed.
So here's a hint:
421 / 10 == 42
421 % 10 == 1
If you want to create an array of the right length, there are various approaches:
you could loop through twice; once to count digits (then create the array); once again to populate
you could populate an array that's bigger than you need, then create a new array and copy in as many members as necessary
you could populate an array that's bigger than you need, then use realloc() or similar (a luxury we didn't used to have!)

How do I manipulate the digits of a number?

In some kinds of problems I often face this situation where I have a variable where I need to rearrange the digits, e.g., int e = 2385;. Let's suppose I don't know which number is stored there, but still I need to shift 2nd and 4th position. When I know variable's value I can simply do e = 2583, but when I don't know I simply can't solve the problem.
Another situation is when I have two values and want to use them to form another number i.e int a = 2, b = 1;, and I need to order them so that I will get a 21 or a 212. I mean, that's easy to do when I'm outputting data, I can simply do:
printf("%d%d\n",a,b);
printf("%d%d%d",a,b,a);
Problem is when I have to store this number in another variable. I don't know how to do that.
This can be broken into two tasks: (1) breaking up a number into pieces, and (2) combining pieces into a whole number.
To break up a number into pieces, use the division and modulus operators.
int num = 2385;
int a = num / 1000; // 2
int b = num / 100 % 10; // 3
int c = num / 10 % 10; // 8
int d = num / 1 % 10; // 5
The trick is to use division to remove the digits to the right, then modulus to keep only the rightmost digit. For example, to calculate the hundreds' place (b) we compute 2385 / 100, which is 23. 23 % 10 is the remainder when you divide 23 by 10. The remainder is 3.
To combine the pieces back into a number, do the opposite with multiplication and addition.
num = a * 1000 // 2000
+ d * 100 // + 500
+ c * 10 // + 80
+ b * 1; // + 3
// ----
// 2583
Notice how I switched d and b to swap those digits.

How to print digit by digit of a number? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Identify the digits in a given number.
I need to print each digit of number without convert it to string. It's possible?
For example:
int n = 1234;
int x;
while( ?? ) {
x = ??
printf("%d\n", x);
}
it prints:
1
2
3
4
I have no idea how to do this. Thanks in advance.
Unless you tell me this isn't homework, I won't give the full answer.
Note that x / 10 gives you x stripped of the last digit. So 123 / 10 = 12, 45 / 10 = 4, etc.
And note that x % 10 gives you the last digit of x. So 123 % 10 = 3, 45 % 10 = 5, etc.
This actually touches on number theory / mathematical methods. You can write a number 1234, for example, as 1x10^3 + 2x10^2 + 3x10^1 + 4x10^0. Now think about how you can use % (mod) and / (integer division) to extract each digit.
If you know the maximum number of digits, you can do it using / and %
so for instance, if you want to find the thousands place, the answer is
num =...
int thousands = (num / 1000) % 10
you can actually do this in a loop

Resources