I want to take user input entered as an integer, for example (45697), and store the first two digits in an array, vector, or something else such as ( 4 5 6 9 7 ), so that I could then use some function call to check for the first two values (4 5) and perform calculations on them.
The Problem: I don't know how to store the recover those first two values.
Is there a simple function call? Or would I have to store the input first as any array and then extract the first two values, and if so, how?
You can do it easily using conversions to/from strings:
>> x = 45697; % or whatever positive value
>> str = num2str(x);
>> y = [str2num(str(1)) str2num(str(2))]
y =
4 5
This assumes that the number x is positive (if it were negative the first character would not be a digit). That seems to be the case, since according to your comments it represents an electrical resistance.
There is nothing wrong with a string-based approach, but here is a mathematical solution to getting all of the digits:
>> x = 45697
x =
45697
>> numDigits = floor(log10(x)+1)
numDigits =
5
>> tens = 10.^(1:numDigits);
>> digitArray = fliplr(floor(mod(x,tens)./(tens/10)))
digitArray =
4 5 6 9 7
The crux of this method is to use mod to chip off the high digits one at a time, shifting the new first digit down to the ones place, and finally truncating down to the get the integer value at that position.
In the case of the OP, the required values are digitArray(1:2).
Since you are interested in individual digits, you don't even need to invoke str2num. One way is enough as in x_str = num2str(x);, then you subtract '0' with y = x_str(1:2)-'0';.
Related
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.
I came across this problem while solving challenges on Hackerrank.
/*
Problem Statement
There are N integers in an array A. All but one integer occur in pairs. Your task is to find the number that occurs only once.
Input Format
The first line of the input contains an integer N, indicating the number of integers. The next line contains N space-separated integers that form the array A.
Constraints
1≤N<100
N % 2=1 (N is an odd number)
0≤A[i]≤100,∀i∈[1,N]
Output Format
Output S, the number that occurs only once.
*/
The normal solution which I would write in this case turned out to be extremely complicated, with lots of nested if loops. On searching a bit, I found this solution which solves the problem by simply XOR-ing all the elements in the integer array with each other, and the result is the lonely integer.
Here's the related method (main() method which accepts input and parses it into integer array not shown as it's not relevant here) :
static int lonelyinteger(int[] a) {
int n = a.length;
int result = 0;
for( int i = 0; i < n; i++) {
result = result ^ a[i];
}
return result;
}
I am not sure how this XOR operation is able to return the "lonely integer" in the array. I'm aware of the two properties of XOR, as:
1. a^a=0
2. a^0=a
But other than this, I couldn't quite figure out how XOR worked here.
There is another question on SO with the same content, but that asks a different question, so I had to ask this (again).
I'd highly appreciate if anyone could provide a detailed explanation for this XOR operation.
Since a^a is equal to 0 for any a, all of the matching pairs of integers will cancel each other out, leaving 0. That is then XOR'ed with the final number. Since 0^a is equal to a for any a, the result will be that final number.
Simple demo:
$ ruby -e 'puts [1,1,2,2,3,3,4,5,5,6,6].reduce :^'
4
You can see why this works if you go through the individual pairs:
1 ^ 1 = 0
0 ^ 2 = 2
2 ^ 2 = 0
0 ^ 3 = 3
3 ^ 3 = 0
0 ^ 4 = 4
4 ^ 5 = 1
1 ^ 5 = 4
4 ^ 6 = 2
2 ^ 6 = 4
The result toggles between 0 and the latest number until you get to the loner; after that it toggles between that number and... whatever you get when you XOR it with the latest new number. The actual value there doesn't matter because it will be zapped when you XOR in the second copy of that number, and you're back to the copy of the singleton.
I sorted the numbers to make it easy to spot the singleton, but since XOR undoes itself, the order doesn't matter at all:
$ ruby -e 'puts [6,3,4,1,1,2,2,6,3,5,5].reduce :^'
4
6 ^ 3 is ... some number, and then that number ^ 4 is some other number, and then you XOR that with 1, and none of that matters because then you undo the 1, and then you throw in another intermediate result with the 2 and undo it right away, and then you undo the 6 and the 3, so you're back to just the 4. Which you XOR with 5 to get another ephemeral number that is then washed away by the final 5, leaving, once again, 4.
I am trying to convert decimal Nos. into binary. The code works pretty fine (Windows 7 , 32 bit MS-VS2010):
int main()
{
int k, n;
int binary[100];
printf("Enter the value in decimal \n ");
scanf("%d", &k);
n = (log(k * 1.0) / log(2 * 1.0)) + 1 ; //total no. of binary bits in this decimal
for (int i = n; i > 0; i--)
{
binary[i] = k % 2;
k /= 2;
}
return 0;
}
But the limitation is that it works for Int size values only i.e. 32 bit. I want to modify this code so that it works for 2048 bits (decimal numbers containing 617 digits actually). I am not allowed to use any library.
Can someone give me some pointers how to proceed to tackle this?
Can someone give an example code snippet say for 64 bits ? Then I can use this to extend to higher values.
Update
1-As per suggestions I am trying to use strings. But I am not able to understand how to convert an String into large Int (I cant use stoi() as thsi will convert to 32 bit int , right? ).
2- Secondly I have to find:
log(222121212213212313133123413131313131311313154515441315413451315641314563154134156313461316413415635154613415645156451434)
Is the library function log capable of finding this ? Then what is the solution?
Since you told that you just need some pointers and not the actual answer, here goes:
I am not able to understand how to convert an String into large Int
That's because you can't. If you want to convert a number that huge to a numerical type, in the first place you need such a type that can hold numbers that big. The language doesn't provide you anything more than long long which is usually 128-bits long (i.e. if you can use C99, or just long which is usually lesser than a long long). Since your tutor told you not to use any external library, it's a clear sign that s/he wants you to code the solution using what's available only in the language and perhaps additionally the standard library.
Is the library function log capable of finding this
No, you can't use stoi or log since all of these expect arguments of some arithmetic type, while none of those built-in types are that big to hold numbers this huge. So you've to work completely with strings (i.e. either static or dynamic char buffers).
I understand that you want to use log to deduce the number of digits the binary output would need; but there's another option, which is to not know the number of digits before hand and allocate them dynamically with some upper bound so that you needn't re-allocate them further.
Lets take an example.
Allocate 3 char buffers in, out (length of input) and bin (length of input * 4).
Copy input to in
While in is not "0" or "1" do else goto 12
For each element ch in in do else goto 10
Convert ch to integer i
If is_odd = 1 then i += 10
quot = i / 2
Append quot to out
is_odd = quot % 2; goto 4
If is_odd = 1 append '1' else '0' to bin
Copy out to in, reset out and goto 3
Append in to bin
Print bin in reverse
When you integer divide a number by 2, the quotient would always be less than or equal to the number of digits of the dividend. So you could allocate in and out with the same size as the input and use it for all iterations. For the bin buffer, the knowledge that each decimal digit wouldn't take more than 4 bits (9 takes a nibble, 1001) would help. So if the input is 10 digits, then 10*4 = 40 bytes would be the upper limit needed for bin buffer and 10 bytes would be needed for the in and out buffers.
This is a vague write-up of an algorithm, I hope it conveys the idea. I feel writing code is more easier than writing algorithms properly.
I'm afraid there are no standard types in C that will allow you to store such a big value with 20148 bits... You can try to read the string from console (not converting into int), and then parse the string into "010101...." on your own.
The approach would be like that:
You should go for "dividing" the string by 2 in each step (for each division by 2 you need to divide all digits of the string by 2, and handle special cases like 11 / 2 => 5), and for each step if the value cannot be divided by 2, then you then you can put "1" as another binary digit, otherwise you put "0". This way you gather the digits '0', '1', '0', '1', etc. one by one. Then finally you need to reverse the order of digits. A similar approach implemented in C# you can find here: Decimal to binary conversion in c #
Regarding the update:
Grinding it through WolframAlpha gives:
log(222121212213212313133123413131313131311313154515441315413451315641314563154134156313461316413415635154613415645156451434)
is roughly
274.8056791141317511022806994521207149274321589939103691837589..
Test:
Putting it into exp gives:
2.2212121221321231313312341313131313131131315451544131541.. × 10^119
This raises the question about the precision you need.
Note: I assumed you mean the natural logarithm (base e).
Does it exist a better way to reverse an element of X?
>> X = dec2bin(10)
X = 1010
I did this:
x(i) = num2str(1-str2num(x(i)))
If I understand you correctly, and you want to set one bit to 1 use bitset
bitset( x, bitNumber)
In case you want to flip a bit from 0 to 1 and vice verca, use bitxor
num = bin2dec('101110');
bitNum = 1;
res = bitxor(num, 2^(bitNum-1));
disp(dec2bin(res));
It is better, because you don't need to convert the number to char .
If you want to flip a bit of a numeric value num without converting it first to a character array of '0' and '1', then you can use functions like BITXOR, BITGET, and BITSET (as Andrey also mentions):
num = bitxor(num, 4); %# Flip the bit in the 4's place (i.e. bit 3)
%# Or ...
num = bitset(num, 3, ~bitget(num, 3)); %# Flip bit 3
However, if you do want to operate on the character array, you could also do this very strange thing:
X(i) = 'a' - X(i);
%# Or ...
X(i) = 97 - X(i);
This works because the characters 'a' and X(i) are first converted to their equivalent Unicode UTF-16 numeric values before the mathematical operation is performed. Since the numeric value for 'a' is 97, then a '0' (numeric value 48) or '1' (numeric value 49) subtracted from 'a' will result in the numeric value for the other. The resulting numeric value on the right hand side of the equation is then converted back to a character when it is placed back in the character array X.
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?