What is Approach behind , to covert string to integer without using built in function. I want to know that how to iteratively solved this problem ?
String to Integer
Extract each digit from the string.
Extracted digit - ‘0’ will actually give the digit value in integer
Because here subtraction will be don on there ascii values. Suppose the extracted digit is ‘2’
So ‘2’ -‘0’=50(asci value of 2)- 48(Ascii value of 0)=2
In this way extract each digit and convert it to a number in int format.
When you extract the 2nd digit from the string:
Number formed till now= 10*(1st digit) + 2nd digit
When you extract the 3rd digit from the string:
Number formed till now= 10*(number formed till 2nd digit) + 3rd digit… and so on…
@pratyush63
In case when write int a=5, it will be converted into the binary format , so char a =‘5’ it will be converted into ascii code ?
I am doing this way ; IS this correct ?
int main() {
char array[] = {'1','2','3','4','\0'}; // must be 5
int len = strlen(array);
int result=0;
for(int i=0; i<len; i++) {
result *= 10;
result += array[i] -'0';
}
cout << result <<endl;
return 0;
}
Yes your approach is correct.
ya thanks @pratyush63 I implemented the same thing in recursion also. but I want to know about that if int a=5, then it will be converted into binary format in memory but when we take char a=‘5’, it will be converted into the assci character?
char a=‘5’ will remain as char only.
It changes to ascii form only when you do some arithmetic operations with it. As you know that you cannot do arithmetic operation on a character…so it gets converted to its ascii form before arithmetic operation is done.
Once converted to ascii form…then the internal operations with it in the computer is done in binary format as always.
@pratyush63
so the conclusion when we are performing the arithematics operation first converted into the ascci then do the opeartion , again converted to char and finally represented in the binary format in computer memory.
So all the char, int represented finally in the bit format Right?
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.