You are here:

C/C language simple program

Advertisement


Question
Write a function that takes a positive integer as input and returns the leading digit in its decimal representation. For example, the leading digit of 234567 is 2.


If you can find me answers in a descriptive manner I'd be very grateful to you.. Thank you much! =)

Answer
Hi Hashane,

The following function will return the leading digit of an unsigned integer.


static unsigned int leading_digit(const unsigned int number)
{
  //buffer to store the number as a string
  char buffer[64];
  //convert the number to a string a store it in the buffer
  sprintf(buffer, "%u", number);
  //return the leading digit as a number by converting the value of the first character to a unsigned integer
  return ((unsigned int)buffer[0] - (unsigned int)'0');
}


-Tony

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Tony Nazzal

Expertise

I will answer any c language programming and syntax questions.

Experience

I have almost a decade of c programming experience.

Education/Credentials
I have a bachelor of science degree and several years of industry experience.

©2016 About.com. All rights reserved.