Infinity numbers array

By A^1^T^E^A^M on Dec 08, 2009

Ok. I have this problem for homework, I soluble it and will post it here, such as my next problems and programs.

Natural numbers are written one by one in infinity array: 12345678910111213... For entered number N by keyboard find the number which is on that position.

Example: If you type 16, the number which need to be write is 1.
123456789101112[u]1[u]3

I test it for n=[1,100] and it works. Just to note that if you work with big numbers you need to change the type of array from int to long, coz you will get overflow.

int brojCifri(int broj){
    int cifri = 0;

    while(broj != 0){
        cifri++;
        broj /= 10;
    }

    return cifri;
}

int najdiCifra(int n){
    if(n<=9) return n;   

    bool done = false;
    int cifri = 11, i = 10;    

    while(!done){    
        if(cifri >= n){  
            done = true;   
        }
        else{
            i++;   
            cifri += brojCifri(i);    
        }
    }

    if(done){
        while(i && cifri>n){   
            i /= 10;
            cifri--;    
        }
        return i%10; 
    }

    return -1;  
}

Comments

Sign in to comment.
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.