How do I find the next multiple of 10 of any integer?

后端 未结 12 1092
Happy的楠姐
Happy的楠姐 2020-12-08 04:15

Dynamic integer will be any number from 0 to 150.

i.e. - number returns 41, need to return 50. If number is 10 need to return 10. Number is 1 need to return 10.

12条回答
  •  春和景丽
    2020-12-08 04:43

    You can do this by performing integer division by 10 rounding up, and then multiplying the result by 10.

    To divide A by B rounding up, add B - 1 to A and then divide it by B using "ordinary" integer division

    Q = (A + B - 1) / B 
    

    So, for your specific problem the while thing together will look as follows

    A = (A + 9) / 10 * 10
    

    This will "snap" A to the next greater multiple of 10.

    The need for the division and for the alignment comes up so often that normally in my programs I'd have macros for dividing [unsigned] integers with rounding up

    #define UDIV_UP(a, b) (((a) + (b) - 1) / (b))
    

    and for aligning an integer to the next boundary

    #define ALIGN_UP(a, b) (UDIV_UP(a, b) * (b))
    

    which would make the above look as

    A = ALIGN_UP(A, 10);
    

    P.S. I don't know whether you need this extended to negative numbers. If you do, care should be taken to do it properly, depending on what you need as the result.

提交回复
热议问题