Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

eek, help!

 
Brandi Love
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I had an assignment in which I had to write a program in which the user enters an integer between 10,000 and 99,999. The program then takes the number, strips the individual digits off (without a tokenizer) and adds them and displays the digits with the result. I figured out that you cold strip the ivdividual digits off by taking the original number and doing a %10 to get the last digit, and then to get the next digit divide the original integer by 10 (and the next by 100, the next by 1,000, etc) and again doing a %10 to get the digit. Now I have to rewrite the program so that it will do the same for ANY positive integer, and I haven't the faintest clue where to start. I know I have to rewrite the equation somehow, but thats about it. Any help would be most greatly appreciated. Here is my code for the original program:
 
William Barnes
Ranch Hand
Posts: 986
Eclipse IDE Firefox Browser Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take what you have and figure out how to put into a loop.
Get the number of digits of the input, and use that as the "max" for your loop.
[ November 02, 2003: Message edited by: William Barnes ]
 
Brandi Love
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
but how can I find the number of digits?
 
fred rosenberger
lowercase baba
Bartender
Posts: 12086
29
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you could write a loop that divides by 10, and when you get a result of 0, you know you're done. i.e. inpu 123
divide by 10, get 12.
divide by 10, get 1
divide by 10, get 0. you're done. you did 3 divisions, so you have a 3 digit number.
or, you could read in a string, get the length, then translate it to an integer
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic