tags:

views:

410

answers:

4

First number needs to be rounded to nearest second number. There are many ways of doing this, but whats the best and shortest algorithm? Anyone up for a challenge :-)

1244->1200
1254->1300
123->100
178->200
1576->1600
1449->1400
123456->123500
654321->654300
23->00
83->100

A: 

Is this homework?

Generally, mod 100, then if >50 add else subtract.

Brian
No its not home work :-)
Senthoor
What the hell Brian! mod and if-then-else that's gonna be really slow. If you're using integers check David's answer. It's a branch-less common way to solve this problem. It works with floating-point numbers as well.
John Leidegren
I myself came up with this answer in Ruby. numbers.each {|number| puts number + '->' + number.gsub(/\d\d\d$/,(number[number.size-3,1].to_i + number[number.size-2,1].to_i / 5).to_s+'00')}
Senthoor
+5  A: 

For input n:

(n + 50) / 100 * 100

using integer division.

Note that many languages/libraries already have functions to do this.

David Zaslavsky
+1  A: 

This will do it, given you're using integer math:

n = (n + 50) / 100 * 100

Of course, you didn't specify the behavior of e.g., 1350 and 1450, so I've elected to round up. If you need round-to-even, that'll not work.

derobert
+2  A: 
100 * round(n/100.0)
Nikhil Chelliah