int to string conversion not working properly - c

I'm trying to create a function that converts an integer into a string, basically what have I done is the following functions: when we get the numbers from the conversion they are reversed so I need a reverse function to make them in the right way. The intostring uses (I think? I got it from some website) the ascii table to convert the number into the string desired.
The problem is: when I enter the 2-digit number they are reversed the wrong way (I guess my reverse function doesn't work that well) and after a certain number of digit the conversion it's not any more accurate.
reverse function:
char reverse(char *stringa) {
int len = strlen(stringa) - 1;
for(int i = 0; i < len / 2; i++) {
char tmp = stringa[i];
stringa[i] = stringa[len - i];
stringa[len - i] = tmp;
}
}
intostring function:
void intostring(int num, char *str) {
int i = 0;
while (num != 0) {
int rem = num % 10;
str[i++] = (rem > 9)? (rem-10) + 'a' : rem + '0';
num = num / 10;
}
str[i] = '\0';
reverse(str);
}

The condition i<len/2 in the reverse function is wrong.
For example, if the string is 2-digit long, len will be 1 and len/2 will be 0. Therefore, no swap will occure while the two characters should be swapped.
the condition should be i<=len/2 or i<len-i.

/*
It works clearly . Checked.
*/
void reverse(char source[],char destination[]) {
int x,i;
//start from last char
i = i=(strlen(source)-1
for (x=0;x<strlen(source);x++){
//Insert char at i in source to x in destination
destination[x]=source[i];
destination[x]='\0';
i--;
}
}

There are multiple problems:
the reverse function fails for an empty string. You should not subtract 1 from the length, but adjust the offset inside the loop.
reverse is defined to return a char but does not return anything. Make it return a char * and return stringa.
intostring produces an empty string for num <= 0. You should loop while num > 9 and add the final digit after the loop.
intostring converts the digit into a character for bases up to 36 (assuming ASCII). This is unnecessarily complex since the base is 10. Use a simpler conversion: str[i++] = '0' + rem;
it may be useful for intostring to return a pointer to the destination array.
Here is a modified version:
#include <string.h>
char *reverse(char *str) {
size_t len = strlen(str);
for (size_t i = 0; i < len / 2; i++) {
char tmp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = tmp;
}
return str;
}
char *intostring(int num, char *str) {
int i = 0;
if (num >= 0) {
while (num > 9) {
str[i++] = '0' + num % 10;
num = num / 10;
}
str[i++] = '0' + num;
} else {
while (num < -9) {
str[i++] = '0' - num % 10;
num = num / 10;
}
str[i++] = '0' - num;
str[i++] = '-';
}
str[i] = '\0';
return reverse(str);
}
Here is an alternative approach for the reverse function using 2 index variables:
#include <string.h>
char *reverse(char *str) {
size_t i = 0;
size_t j = strlen(str);
while (j --> i) {
char c = str[j];
str[j] = str[i];
str[i++] = c;
}
return str;
}

The reverse function condition is worng.
If the integer in 32 then the string will be
s[0] = '2', s[1] = '3', s[2] = '\0' before string reversal.
so in reverse function the following swap operation has to be applied as
if number = 32 then len = 2
i = 0 then len - i - 1 = 1
so 0 and 1 will be swaped.
void reverse(char *stringa){
int len = strlen(stringa);
for(int i = 0; i < len / 2; i++){
char tmp = stringa[i];
stringa[i] = stringa[len - i - 1];
stringa[len - i - 1] = tmp;
}
}
void intostring(int num, char *str)
{
int i = 0;
if(num == 0){
str[i++] = '0';
str[i] = '\0';
}
else if(num > 0){
while(num != 0){
int rem = num % 10;
str[i++] = '0' + rem;
num = num/10;
}
str[i] = '\0';
}
else{
while(num != 0){
int rem = num % 10;
/*
(-5/2) => -2
-2 * 2 => -4
so a%b => -1
(5/-2) => -2
-2 * -2 => 4
so a%b => 1
*/
rem = abs(rem); // as the rem value is negative
str[i++] = '0' + rem;
num = num/10;
}
str[i++] = '-';
str[i] = '\0';
}
reverse(str);
}

Your reverse function is wrong. You can make it correct (and readable) like below:
void reverse(char *stringa) {
int i = 0; //Forwarding moving index
int j = strlen(stringa) - 1; // the end index
int tmp; // Edited to get the code compiled
for (; i < j; i++, j--) {
tmp = stringa[i];
stringa[i] = stringa[j];
stringa[j] = tmp;
}
}

Related

how to write a function char* in c that returns words sorted in order of their length?

Write a function that takes a string as a parameter and returns its words sorted in order of their length first and then in alphabetical order on line separated by '^'
here is examples of output
There will be only spaces, tabs and alphanumeric caracters in strings.
You'll have only one space between same size words and ^ otherwise.
A word is a section of string delimited by spaces/tabs or the start/end of the string. If a word has a single letter, it must be capitalized.
A letter is a character in the set [a-zA-Z]
here is my code, but it returns nothing I think issue in last function....
#include <unistd.h>
#include <stdlib.h>
int is_upper(char c)
{
return c >= 'A' && c <= 'Z';
}
int my_lower(char c)
{
if (is_upper(c))
return c + 32;
return c;
}
int my_strlen(char *s)
{
int i = 0;
for (; s[i]; i++)
;
return i;
}
int my_is(char c)
{
return c == ' ' || c == '\t';
}
char *my_strsub(char *s, int start, int end)
{
char *res = malloc(end - start);
int i = 0;
while (start < end)
res[i++] = s[start++];
res[i] = 0;
return res;
}
int cmp_alpha(char *a, char *b)
{
while (*a && *b && *a == *b)
{
a++;
b++;
}
return my_lower(*a) <= my_lower(*b);
}
int cmp_len(char *a, char *b)
{
return my_strlen(a) <= my_strlen(b);
}
void my_sort(char *arr[], int n, int(*cmp)(char*, char*))
{
char *tmp;
for (int i = 0; i < n; i++)
for (int j = 0; j < n - 1; j++)
{
if ((*cmp)(arr[j], arr[j + 1]) == 0)
{
tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
}
}
char* long(char *s)
{
int start = 0, idx = 0;
char *words[my_strlen(s) / 2 + 1];
for (int i = 0; s[i]; i++)
{
if (!my_is(s[i]) && i > 0 && my_is(s[i - 1]))
start = i;
if (my_is(s[i]) && i > 0 && !my_is(s[i - 1]))
words[idx++] = my_strsub(s, start, i);
if (!s[i + 1] && !my_is(s[i]))
words[idx++] = my_strsub(s, start, i + 1);
}
my_sort(words, idx, &cmp_alpha);
my_sort(words, idx, &cmp_len);
char* res = malloc(100);
int pushed=0;
for (int i = 0; i < idx - 1; i++)
{
res[pushed]=*words[i];
if (my_strlen(&res[pushed]) < my_strlen(&res[pushed + 1]))
{
res[pushed]=res[94];
}
else
{
res[pushed]=res[32];
}
pushed++;
}
res[pushed]='\0';
return res;
}
int main()
{
long("Never take a gamble you are not prepared to lose");
return 0;
}
Apart from the off-by-one allocation error in my_strsub, separating and sorting the words seems to work well. Only then you confuse the result character array with a character pointer array, e. g. with res[pushed]=*words[i] you write only the first character of a word to the result. The last for loop of ord_alphlong could rather be:
if (idx)
for (int i = 0; ; )
{
char *word = words[i];
int lng = my_strlen(word);
if (100 < pushed+lng+1) exit(1); // too long
for (int i = 0; i < lng; ) res[pushed++] = word[i++];
if (++i == idx) break; // last word
res[pushed++] = lng < my_strlen(words[i]) ? '^' // other size
: ' '; // same size
}
Of course in order to see the result of the function, you'd have to output it somehow.

Is binary to decimal conversion rounded? how?

Got to transform a binary number to decimal for recoding printf (no lib or functions allowed except malloc and write). i'm doing my calculs on char *, so it can't overflow. But when i hit a certain size, my result differ from a online binary converter, and i noticed that the binary converter keep always only 20 digits.
for exemple :
binary : 1.11111111111111111111111111
binary converter = 1.99999998509883880615,
my o converter == 1.99799896499882880605234375,
I guess the online converter keep the result rounded in an unsigned long long, but i don't understand how this rounding is calculated.
Do you have any clues?
Here is my code:
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
char *ft_binary_pow(char *tmp, int i)
{
int j;
int div;
int remnant;
j = 0;
remnant = 0;
tmp[0] = '1';
tmp.sign = 0;
while (i > 0)
{
while (isdigit(tmp[j]) || remnant != 0)
{
if (tmp[j])
div = ((tmp[j] - '0') * 10) / 2;
else
div = 0;
tmp[j] = ((div / 10) + remnant) + '0';
remnant = div % 10;
j++;
}
j = 0;
i--;
}
return (tmp);
}
char *ft_add_tmp(char *ret, char *tmp)
{
int i;
int j;
int add;
int remnant;
i = strlen(tmp);
add = 0;
remnant = 0;
while (--i >= 0)
{
if (!ret[i])
add = tmp[i] - '0';
else
add = (ret[i] - '0') + (tmp[i] - '0');
if ((add % 10 + remnant) < 10)
ret[i] = (add % 10 + remnant) + '0';
else
ret[i] = '0';
remnant = add / 10 ? 1 : 0;
}
return (ret);
}
int main(void)
{
int i;
char *lol = "11111111111111111111111111";
char *ret;
char *tmp;
if (!(ret = (char *)calloc(340, sizeof(char))))
return (0);
i = 0;
ret[0] = '1';
while (lol[i])
{
if (lol[i] == '1')
{
if (!(tmp = (char *)calloc(50, sizeof(char))))
return (0);
tmp = ft_binary_pow(tmp, i + 1);
ret = ft_add_tmp(ret, tmp);
free(tmp);
}
i++;
}
printf("ret = %s\n", ret);
return (0);
}
Edited for more readable code
Thanks for your time!
Code fails even with lol = "111111111".
Code fails in ft_add_tmp() to handle a carry (overflow) into the next most significant digit.
else {
ret.decimal[i] = '0';
// add something like this and then also prorogate carry as needed to higher digits
ret.decimal[i-1]++;
}
Suggested correction and simplification:
char* ft_add_tmp(char *ret, const char *tmp) {
size_t i = strlen(tmp);
unsigned carry = 0;
while (i-- > 0) {
unsigned sum = ret[i] ? ret[i] - '0' : 0;
sum += tmp[i] - '0' + carry;
ret[i] = sum % 10 + '0';
carry = sum / 10;
}
assert(carry == 0);
return (ret);
}

How to identify the bug in my Alphacode implementation?

The following is my implementation of the problem: http://www.spoj.com/problems/ACODE/
#include <stdio.h>
#include <string.h>
int main() {
long long int dp[5010] = { 0 }, i, len, ans;
char str[5010];
scanf("%s", str);
while (str[0] != '0') {
len = strlen(str);
dp[0] =1;
for (i = 1; i < len; i++) {
ans = (str[i-1] * 10 + str[i]);
if (str[i] - '0')
dp[i] = str[i];
if (ans >= 10 && ans <= 26) {
if ((i - 2) < 0)
dp[i] += dp[0];
else
dp[i] += dp[i-2];
}
}
scanf("%s", str);
}
printf("%llu\n", dp[len-1]);
return 0;
}
When I run it in my IDE, it gets executed but the output is completely different from expected. Also when I run it on Ideone it shows "time limit exceeded". Please help me in finding my mistake.
There are several errors:
You print the result only once, for the last string. You should, of course, print a result for all strings. Your code currently looks like this:
scanf("%s",str);
while (str[0] != '0') {
// determine solution
scanf("%s", str);
}
printf("%llu\n", dp[len-1]);
The printf should go before the last scanf.
This:
ans = (str[i - 1] * 10 + str[i]);
is a calculation on ASCII codes. You need somethingb like this:
ans = ((str[i - 1] - '0') * 10 + str[i] - '0');
The code
if (str[i] - '0') dp[i] = str[i];
should handle substrings that begin with a zero, but it leaves dp[i] effectively uninitialised (or filled with garbage from a previous string) for such strings.
The principal error is that you attack the problem from the wrong end, though. When you go forward through the string, your algorithm loks like this:
if the next two digits are a number from 10 to 26:
dp[i] = dp[i + 1] + dp[i + 2]
else if the current digit isn't zero:
dp[i] = dp[i + 1]
else:
dp[i] = 0
That code requires knowledge of dp[j] with j > i in order to calculate dp[i]. That means that you can solve the problem by walking through the array backwards. Your solution is then dp[0].
Because you only look forward one or two digits, you don't even need an auxiliary array; it is enough to keep the last two values and swap them accordingly after each iteration.
Here's a solution that does this. It has only been tested for the given cases, but it should give you an idea how to solve your problem. The code doesn't do a lot of checking; it is assumed that the string has only digits.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
unsigned long long poss(const char *str)
{
unsigned long long p1, p2;
size_t len = strlen(str);
size_t i;
if (len == 0) return 0;
i = len - 1;
p1 = 1;
p2 = 1;
if (str[i] == '0') p1 = 0;
while (i-- > 0) {
unsigned long long p = p1;
if (str[i] == '0') p = 0;
if (str[i] == '1') p += p2;
if (str[i] == '2' && str[i + 1] < '7') p += p2;
p2 = p1;
p1 = p;
}
return p1;
}
int main(void)
{
char str[5001];
while(scanf("%s",str) == 1 && str[0] != '0') {
printf("%llu\n", poss(str));
}
return 0;
}
What you need is a recursive function whitch divides if you find somthing in between 10 and 26
long long int count_decodings( const char * str )
{
long long int count = 1;
// only accept digits
// continue while next character greater or equal '0' and less or equal '9'
while ( ( *str >= '0' && *str <= '9' ) )
{
char actChar = *str;
str ++; // increment string pointer ( now str points to character after actChar )
if ( actChar == '1' && ( *str >= '0' && *str <= '9' ) )
{
// if we have 1 followed by somthing from 0 to 9 we have an new case
count += count_decodings( str + 1 ); // continue with next sign and increment count of decodings
}
else if ( actChar == '2' && ( *str >= '0' && *str <= '6' ) )
{
// if we have 2 followed by somthing from 0 to 6 we have an new case
count += count_decodings( str + 1 ); // continue with next sign and increment count of decodings
}
}
return count;
}
int main()
{
char str[5010];
scanf("%s",str);
while(str[0]!=0)
{
long long int count = count_decodings( str );
printf( "%llu\n", count);
scanf("%s", str);
}
return 0;
}

C Code for Hexadecimal without using standard libraries

I want to write C Code which converts first string into integer then integer into hexadecimal.
ex: I have Ip iddress as "172.24.18.240" now first find out first dot from it and take the number before it that is "172" convert it into integer then convert it inti hexadecimal and it should do the same for all like 24,18,240 and convert into long/integer value
any help is appreciated.
#include <stdio.h> // testing
int main(int argc, char** argv) // testing
{
char* ipString = argc > 1? argv[1] : "172.24.18.240"; // testing
char* ip = ipString;
unsigned int hex;
for( int i = 0; i < 4; i++ ){
unsigned int n = 0;
for( char c; (c = *ip) >= '0' && c <= '9'; ip++ )
n = 10 * n + c - '0';
hex = (hex << 8) + n;
if( *ip == '.' ) ip++;
}
printf("%08X\n", hex); // testing
return 0; // testing
}
Maybe something like this?
char sn[4];
char *nid = hexString;
int nip[4];
int xnip[4];
int j = 0;
while (*nid != '\0') {
int i = 0;
memset(sn, '\0', sizeof sn);
while (isdigit(*nid)) {
sn[i++] = *nid++;
}
if (*nid == '.')
nid++;
// now sn should be the number part
nip[j] = your_str_to_int(sn);
xnip[j] = your_int_to_hex(nip[j]);
j++;
}
int main(void)
{
char hexChars[] = "0123456789ABCDEF";
char ipString[] = "172.24.18.254";
char hexString[9] = "";
const char* pch = ipString;
int num = 0;
int i = 0;
do
{
if (*pch != '.' && *pch != '\0')
{
num *= 10;
num += (*pch - '0');
}
else
{
hexString[i++] = hexChars[num / 16];
hexString[i++] = hexChars[num % 16];
num = 0;
}
} while (*pch++);
return 0;
}
The hex values will stored in hexString.
int i = 0, sum = 0;
char ipString[] = "172.24.18.240";
do
{
if (isdigit(ipString[i])) sum = sum * 10 + ipString[i] - '0';
else
{ putchar("0123456789ABCDEF"[sum / 16]);
putchar("0123456789ABCDEF"[sum % 16]);
putchar('.');
sum = 0;
}
}
while (ipString[i++] != '\0');
More or less ugly, but should work on IP addresses.

Convert integer to string without access to libraries

I recently read a sample job interview question:
Write a function to convert an integer
to a string. Assume you do not have
access to library functions i.e.,
itoa(), etc...
How would you go about this?
fast stab at it: (edited to handle negative numbers)
int n = INT_MIN;
char buffer[50];
int i = 0;
bool isNeg = n<0;
unsigned int n1 = isNeg ? -n : n;
while(n1!=0)
{
buffer[i++] = n1%10+'0';
n1=n1/10;
}
if(isNeg)
buffer[i++] = '-';
buffer[i] = '\0';
for(int t = 0; t < i/2; t++)
{
buffer[t] ^= buffer[i-t-1];
buffer[i-t-1] ^= buffer[t];
buffer[t] ^= buffer[i-t-1];
}
if(n == 0)
{
buffer[0] = '0';
buffer[1] = '\0';
}
printf(buffer);
A look on the web for itoa implementation will give you good examples. Here is one, avoiding to reverse the string at the end. It relies on a static buffer, so take care if you reuse it for different values.
char* itoa(int val, int base){
static char buf[32] = {0};
int i = 30;
for(; val && i ; --i, val /= base)
buf[i] = "0123456789abcdef"[val % base];
return &buf[i+1];
}
The algorithm is easy to see in English.
Given an integer, e.g. 123
divide by 10 => 123/10. Yielding, result = 12 and remainder = 3
add 30h to 3 and push on stack (adding 30h will convert 3 to ASCII representation)
repeat step 1 until result < 10
add 30h to result and store on stack
the stack contains the number in order of | 1 | 2 | 3 | ...
I would keep in mind that all of the digit characters are in increasing order within the ASCII character set and do not have other characters between them.
I would also use the / and the% operators repeatedly.
How I would go about getting the memory for the string would depend on information you have not given.
Assuming it is in decimal, then like this:
int num = ...;
char res[MaxDigitCount];
int len = 0;
for(; num > 0; ++len)
{
res[len] = num%10+'0';
num/=10;
}
res[len] = 0; //null-terminating
//now we need to reverse res
for(int i = 0; i < len/2; ++i)
{
char c = res[i]; res[i] = res[len-i-1]; res[len-i-1] = c;
}
An implementation of itoa() function seems like an easy task but actually you have to take care of many aspects that are related on your exact needs. I guess that in the interview you are expected to give some details about your way to the solution rather than copying a solution that can be found in Google (http://en.wikipedia.org/wiki/Itoa)
Here are some questions you may want to ask yourself or the interviewer:
Where should the string be located (malloced? passed by the user? static variable?)
Should I support signed numbers?
Should i support floating point?
Should I support other bases rather then 10?
Do we need any input checking?
Is the output string limited in legth?
And so on.
Convert integer to string without access to libraries
Convert the least significant digit to a character first and then proceed to more significant digits.
Normally I'd shift the resulting string into place, yet recursion allows skipping that step with some tight code.
Using neg_a in myitoa_helper() avoids undefined behavior with INT_MIN.
// Return character one past end of character digits.
static char *myitoa_helper(char *dest, int neg_a) {
if (neg_a <= -10) {
dest = myitoa_helper(dest, neg_a / 10);
}
*dest = (char) ('0' - neg_a % 10);
return dest + 1;
}
char *myitoa(char *dest, int a) {
if (a >= 0) {
*myitoa_helper(dest, -a) = '\0';
} else {
*dest = '-';
*myitoa_helper(dest + 1, a) = '\0';
}
return dest;
}
void myitoa_test(int a) {
char s[100];
memset(s, 'x', sizeof s);
printf("%11d <%s>\n", a, myitoa(s, a));
}
Test code & output
#include "limits.h"
#include "stdio.h"
int main(void) {
const int a[] = {INT_MIN, INT_MIN + 1, -42, -1, 0, 1, 2, 9, 10, 99, 100,
INT_MAX - 1, INT_MAX};
for (unsigned i = 0; i < sizeof a / sizeof a[0]; i++) {
myitoa_test(a[i]);
}
return 0;
}
-2147483648 <-2147483648>
-2147483647 <-2147483647>
-42 <-42>
-1 <-1>
0 <0>
1 <1>
2 <2>
9 <9>
10 <10>
99 <99>
100 <100>
2147483646 <2147483646>
2147483647 <2147483647>
The faster the better?
unsigned countDigits(long long x)
{
int i = 1;
while ((x /= 10) && ++i);
return i;
}
unsigned getNumDigits(long long x)
{
x < 0 ? x = -x : 0;
return
x < 10 ? 1 :
x < 100 ? 2 :
x < 1000 ? 3 :
x < 10000 ? 4 :
x < 100000 ? 5 :
x < 1000000 ? 6 :
x < 10000000 ? 7 :
x < 100000000 ? 8 :
x < 1000000000 ? 9 :
x < 10000000000 ? 10 : countDigits(x);
}
#define tochar(x) '0' + x
void tostr(char* dest, long long x)
{
unsigned i = getNumDigits(x);
char negative = x < 0;
if (negative && (*dest = '-') & (x = -x) & i++);
*(dest + i) = 0;
while ((i > negative) && (*(dest + (--i)) = tochar(((x) % 10))) | (x /= 10));
}
If you want to debug, You can split the conditions (instructions) into
lines of code inside the while scopes {}.
I came across this question so I decided to drop by the code I usually use for this:
char *SignedIntToStr(char *Dest, signed int Number, register unsigned char Base) {
if (Base < 2 || Base > 36) {
return (char *)0;
}
register unsigned char Digits = 1;
register unsigned int CurrentPlaceValue = 1;
for (register unsigned int T = Number/Base; T; T /= Base) {
CurrentPlaceValue *= Base;
Digits++;
}
if (!Dest) {
Dest = malloc(Digits+(Number < 0)+1);
}
char *const RDest = Dest;
if (Number < 0) {
Number = -Number;
*Dest = '-';
Dest++;
}
for (register unsigned char i = 0; i < Digits; i++) {
register unsigned char Digit = (Number/CurrentPlaceValue);
Dest[i] = (Digit < 10? '0' : 87)+Digit;
Number %= CurrentPlaceValue;
CurrentPlaceValue /= Base;
}
Dest[Digits] = '\0';
return RDest;
}
#include <stdio.h>
int main(int argc, char *argv[]) {
char String[32];
puts(SignedIntToStr(String, -100, 16));
return 0;
}
This will automatically allocate memory if NULL is passed into Dest. Otherwise it will write to Dest.
Here's a simple approach, but I suspect if you turn this in as-is without understanding and paraphrasing it, your teacher will know you just copied off the net:
char *pru(unsigned x, char *eob)
{
do { *--eob = x%10; } while (x/=10);
return eob;
}
char *pri(int x, char *eob)
{
eob = fmtu(x<0?-x:x, eob);
if (x<0) *--eob='-';
return eob;
}
Various improvements are possible, especially if you want to efficiently support larger-than-word integer sizes up to intmax_t. I'll leave it to you to figure out the way these functions are intended to be called.
Slightly longer than the solution:
static char*
itoa(int n, char s[])
{
int i, sign;
if ((sign = n) < 0)
n = -n;
i = 0;
do
{
s[i++] = n % 10 + '0';
} while ((n /= 10) > 0);
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
return s;
}
Reverse:
int strlen(const char* str)
{
int i = 0;
while (str != '\0')
{
i++;
str++;
}
return i;
}
static void
reverse(char s[])
{
int i, j;
char c;
for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
And although the decision davolno long here are some useful features for beginners. I hope you will be helpful.
This is the shortest function I can think of that:
Correctly handles all signed 32-bit integers including 0, MIN_INT32, MAX_INT32.
Returns a value that can be printed immediatelly, e.g.: printf("%s\n", GetDigits(-123))
Please comment for improvements:
static const char LARGEST_NEGATIVE[] = "-2147483648";
static char* GetDigits(int32_t x) {
char* buffer = (char*) calloc(sizeof(LARGEST_NEGATIVE), 1);
int negative = x < 0;
if (negative) {
if (x + (1 << 31) == 0) { // if x is the largest negative number
memcpy(buffer, LARGEST_NEGATIVE, sizeof(LARGEST_NEGATIVE));
return buffer;
}
x *= -1;
}
// storing digits in reversed order
int length = 0;
do {
buffer[length++] = x % 10 + '0';
x /= 10;
} while (x > 0);
if (negative) {
buffer[length++] = '-'; // appending minus
}
// reversing digits
for (int i = 0; i < length / 2; i++) {
char temp = buffer[i];
buffer[i] = buffer[length-1 - i];
buffer[length-1 - i] = temp;
}
return buffer;
}
//Fixed the answer from [10]
#include <iostream>
void CovertIntToString(unsigned int n1)
{
unsigned int n = INT_MIN;
char buffer[50];
int i = 0;
n = n1;
bool isNeg = n<0;
n1 = isNeg ? -n1 : n1;
while(n1!=0)
{
buffer[i++] = n1%10+'0';
n1=n1/10;
}
if(isNeg)
buffer[i++] = '-';
buffer[i] = '\0';
// Now we must reverse the string
for(int t = 0; t < i/2; t++)
{
buffer[t] ^= buffer[i-t-1];
buffer[i-t-1] ^= buffer[t];
buffer[t] ^= buffer[i-t-1];
}
if(n == 0)
{
buffer[0] = '0';
buffer[1] = '\0';
}
printf("%s", buffer);
}
int main() {
unsigned int x = 4156;
CovertIntToString(x);
return 0;
}
This function converts each digits of number into a char and chars add together
in one stack forming a string. Finally, string is formed from integer.
string convertToString(int num){
string str="";
for(; num>0;){
str+=(num%10+'0');
num/=10;
}
return str;
}

Resources