Showing posts with label conversion. Show all posts
Showing posts with label conversion. Show all posts

Tuesday, December 8, 2009

Integer to String

 String intToStr( int num ){
    int i = 0;
    boolean isNeg = false;
    /* Buffer big enough for largest int and - sign */
    char[] temp = new char[ MAX_DIGITS + 1 ];

    /* Check to see if the number is negative */
    if( num < 0 ){
        num *= -1;
        isNeg = true;
    }

    /* Fill buffer with digit characters in reverse order */
    do {
        temp[i++] = (char)((num % 10) + '0');
        num /= 10;
    } while( num != 0 );

    StringBuffer b = new StringBuffer();
    if( isNeg )
        b.append( '-' );

    while( i > 0 ){
        b.append( temp[--i] );
    }

    return b.toString();
}

String to Integer

int strToInt( string str ){
    int i = 0, num = 0;
    bool isNeg = false;
    int len = str.Length();

    if( str[0] == '-' ){
        isNeg = true;
        i = 1;
    }

    while( i < len ){
        num *= 10;
        num += ( str[i++] - '0' );
    }

    if( isNeg )
        num *= -1;

    return num;
}