-6

I have an 'n' digit number. I need to print the first n - 1 digits of the same. As far as I know, it is basically division by 10. But this is to be done without using any of the arithmetic operators. I tried using some of the conversions in ctype, but since the exact length of the number, i.e. no. of digits is not known, I am unable to use the same.

i.e.

convert int to string, say 12345 to string

set the last position of it to '\0', in my case last position is not known

//i.e. 1, 2, 3, 4, '\0', assuming string size is 5

convert it back to int.// 1234

Is there any tweak, or something entirely different available for this?

user2053912
  • 173
  • 1
  • 3
  • 11
  • By the way, converting the int to a string WILL involve arithmetics - ok, so you may be able to do it using standard functions, but they will use arithmetic. – Mats Petersson Mar 02 '13 at 10:43
  • how do you get the "number", does the user type it in, or is it an int you've typed into your program? – Josh Petitt Mar 02 '13 at 12:44

1 Answers1

2

Use sprintf() to convert your int to a string. You'll need a char buffer[SOMESIZE]; to pass into sprintf. Now you have a string, that you can manipulate. strlen() will give you the length of it [1]. The rest should follow what you outlined.

I'll let you figure out exactly how to put the bits together.

[1] Actually, you could use the return value from sprintf as length, since it returns the number of characters produced in the string.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227