Getting a certain digit from decimal in C - c

I have int x = 346.
I need to get in turn, each time a new digit of it, so first 3, then 4, then 6.
Using floor does not help me here,
and other examples here give only the left/right digit.
Is there a simple algorithm?

a%10 gives you the last digit of a number i.e. its remainder when divided by 10. You can print all the digits of a number like so:
void print_digits(int a) {
while (a > 0) {
printf("%d\n", a%10);
a /= 10;
}
}
This will print the digits from least significant to most significant. You can get them in reverse order if you use an auxiliary stack for instance.

Related

What is the most efficient (speed) way to get a digit from a larger number?

I plan to use this inside a game loop to draw the score using custom bitmap font.
Here is what I have. Now I know that I have used the modulus, division and power operators a bunch of times. I understand that using this in a game loop is not a good thing to do. Any suggestions?
// Get digit n, where n is digit starting from the units place and moving left
int getDigit(int number, int position)
{
return (number % (int)pow(10, position)) / pow(10, (position - 1));
}
If int is 32 bits, then:
static const int table[] =
{ 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 };
return number / table[position-1] % 10;
is a reasonable implementation:
It does not invoke pow or use floating-point arithmetic.
It uses one table look-up, one division by a variable, and one remainder operation with a constant (which a compiler can optimize to a multiplication and some shifts and adds).
(Note that position is adjusted in the table lookup to be one-based to match the code in the question, but common practice would be to call the units position position 0 instead of position 1.)
If digits are to be extracted for multiple positions or the whole number, then other implementations should be considered.
You said that you extract a digit in order to display the game score; so I assume you will use the whole original number.
You can extract all the digits in a loop this way:
int number = 1234; // this variable will be consumed
while (number) {
rightmostdigit = number % 10;
// do something with the extracted digit
number /= 10; // discard the rightmost at go to the next
}
The above routine extracts digits from the right, so the score shall be drawn from right to left. Warning that if the number is zero, the loop is never executed...
If you want to extract from left, and supposing a fixed-length score (like "00123"), you can store the single digits in an array, then read them back in the inverse direction: it should be faster than trying to extract the digits from left to right.

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 can I iterate through each digit in a 3 digit number in C?

Length is always 3, examples:
000
056
999
How can I get the number so I can use the value of the single digit in an array?
Would it be easier to convert to an char, loop through it and convert back to int when needed?
To get the decimal digit at position p of an integer i you would do this:
(i / pow(p, 10)) % 10;
So to loop from the last digit to the first digit, you would do this:
int n = 56; // 056
int digit;
while(n) {
digit = n % 10;
n /= 10;
// Do something with digit
}
Easy to modify to do it exactly 3 times.
As Austin says, you can easily find answers on Google. But it basically involves mod-by-10, then divide-by-ten. Assuming integers.

Recursive function that sums the odd digits of an integer

For instance n = 8135267 => 16
Here is a solution but I don't understand it.
int sumOddDigits(int n) {
if(n == 0)
return 0;
if(n%2 == 1) //if n is odd
//returns last digit of n + sumOddDigits(n/10) => n/10 removes the last digit of n
return n % 10 + sumOddDigits(n/10)
else
return sumOddDigits(n/10);
}
Integer divison by ten "cuts off" the last digit: I.e. 1234/10 results in 123.
Modulo 10 returns the last digit: i.e. 1234%10 results in 4.
Thus, the above code considers always the last digit. If the last digit is odd (hence the %2==1 stuff) it will be counted, otherwise not. So, if it should count the digit, it takes the last digit (the % 10-stuff) and continues computing with the remaining digits (the recursion with the /10-stuff) and adding them to the digit. If the current digit shall not be counted, it continues just with the remaining digits (thus the recursion and the /10-stuff) without adding it to the current digit.
If the argument is 0, this means that the whole number is traversed, thus the function terminates with returning 0.
% is the modulo operator. It basically finds the remainder of dividing by a number.
n %2 n is only 1 if it's odd. % 10 gets the remainder of the dividing the number by 10, this gets you the currently last digit. Integer division by 10 gets you the next digit as the current last digit (1567/10 = 156)
Think about it this way: Starting with your known answer of 8135267 => 16, if I asked you for the sum of the odd digits in *3*8135267, what would you do? What if I asked for *4*8135267? How do your manual steps related to that function?
Think of it this way. If you get an even digit your function returns it + function value of the number without that digit. Otherwise it returns the function value of the number without the last digit. On your example:
813526(7) -> 0 + sumEvenDigits(813526)
6 + sumEvenDigits(81352)
2 + sumEvenDigits(8135)
....
8 + sumEvenDigits(0)
0 = 16
Hope this helps.
int sum_odd_digits(int n)
{
int s=0,r=0;
if(n==0)
return 0;
r = n%10;
if(r%2==1)
s = s+r;
n=n/10;
return s+ sum_odd_digits(n);
}

Resources