C ++ decimal integer delimiter

Source: Internet
Author: User

The original question titled A game company is as follows: write a thousand-bit separator algorithm, and the function prototype is char * format_thousands_separator (unsigned long val). The expected effect is 1. the user does not need to release the returned string pointer 2. A maximum of 16 calls are supported without returning the same pointer address. You can use the following methods to test
Printf ("num1 (% s), num2 (% s), num3 (% s)", format_thousands_separator (0), format_thousands_separator (123456), format_thousands_separator (23456789 ));
Note: Compile the code that can be compiled and run.

After modification, the simplest C code is described as follows:
1char * format_thousands_separator (unsigned long val)
2 {
3 static char buf [16] [16];
4 static int c = 0;
5
6 long m, n = 0;
7 char * p = & buf [c ++ % 16] [15];
8 * p =;
9
10 do
11 {
12 m = val % 10;
13 val = val/10;
14 * -- p = 0 + m;
15
16 if (val &&! (++ N % 3 ))
17 * -- p = ,;
18
19} while (val );
20
21 return p;
22}
Here we will make a slight extension to support negative numbers. The code description is as follows:
1char * format_thousands_separator (long val)
2 {
3 static char buf [16] [16];
4 static int c = 0;
5
6 long m, n = 0;
7 char * p = & buf [c ++ % 16] [15];
8 * p =;
9
10 do
11 {
12 m = val % 10;
13 val = val/10;
14 * -- p = 0 + (m <0? -M: m );
15
16 if (! Val & m <0)
17 * -- p = -;
18
19 if (val &&! (++ N % 3 ))
20 * -- p = ,;
21
22} while (val );
23
24 return p;
25}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.