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

后端 未结 12 1089
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:40
    n + (((9 - (n % 10)) + 1) % 10)
    
    0 讨论(0)
  • 2020-12-08 04:41

    in C, one-liner:

    int inline roundup10(int n) {
      return ((n - 1) / 10 + 1) * 10;
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-08 04:43

    What about ((n + 9) / 10) * 10 ?

    Yields 0 => 0, 1 => 10, 8 => 10, 29 => 30, 30 => 30, 31 => 40

    0 讨论(0)
  • 2020-12-08 04:48

    How about using integer math:

    N=41
    N+=9   // Add 9 first to ensure rounding.
    N/=10  // Drops the ones place
    N*=10  // Puts the ones place back with a zero
    
    0 讨论(0)
  • 2020-12-08 04:49

    Be aware that answers based on the div and mod operators ("/" and "%") will not work for negative numbers without an if-test, because C and C++ implement those operators incorrectly for negative numbers. (-3 mod 5) is 2, but C and C++ calculate (-3 % 5) as -3.

    You can define your own div and mod functions. For example,

    int mod(int x, int y) {
      // Assert y > 0
      int ret = x % y;
      if(ret < 0) {
        ret += y;
      }
      return ret;
    }
    
    0 讨论(0)
提交回复
热议问题