आसान 0 हल किए गए 0% स्वीकृति

Sum a Flat JSON Object

Parse a flat JSON object whose values are integers and add up the values.

आप क्या सीखेंगे

  • Read key-value pairs from JSON text
  • Handle spaces and negative numbers
  • Sum values in a 64-bit integer

समस्या

अनुवाद दिखाएँ

Programs often receive JSON such as {"apples": 3, "pears": 5}. Libraries like System.Text.Json parse it for you, but parsing a simple case by hand shows how the format works.

The input is a flat JSON object: {, then zero or more "key": value pairs separated by commas, then }. Keys are quoted and contain no quotes, commas or colons; values are integers, possibly negative. Spaces may appear around any of the symbols.

Implement sum_json_numbers(text).

Input

text: The JSON object.

Output

Return the sum of all values (0 for an empty object).

सीमाएँ

2 ≤ length of text ≤ 100,000

At most 10,000 pairs; every value and the sum fit in a 64-bit integer

उदाहरण

उदाहरण 1
इनपुट:
text = "{\"apples\": 3, \"pears\": 5}"

अपेक्षित आउटपुट:
expected = 8
इनपुट:
std::string text = "{\"apples\": 3, \"pears\": 5}";

अपेक्षित आउटपुट:
long long expected = 8;
इनपुट:
string text = "{\"apples\": 3, \"pears\": 5}";

अपेक्षित आउटपुट:
long expected = 8;

व्याख्या

3 + 5 = 8.

उदाहरण 2
इनपुट:
text = "{ \"debt\" : -20 , \"cash\":15 }"

अपेक्षित आउटपुट:
expected = -5
इनपुट:
std::string text = "{ \"debt\" : -20 , \"cash\":15 }";

अपेक्षित आउटपुट:
long long expected = -5;
इनपुट:
string text = "{ \"debt\" : -20 , \"cash\":15 }";

अपेक्षित आउटपुट:
long expected = -5;

व्याख्या

Spaces around the symbols do not matter: −20 + 15 = −5.

कैसे हल करें

पहले खुद कोशिश करें, फिर एक-एक करके संकेत खोलें।

संकेत 1

Remove the braces, then split the pairs at commas.

संकेत 2

Each value is the text after the colon; trim spaces before converting.

संकेत 3

Use a 64-bit integer and return 0 for an empty object.

अपेक्षित जटिलता

O(length of text) time, O(1) extra space

संदर्भ

यह चुनौती CodeUtility के लिए अनुकूलित की गई है। ऊपर दिए गए स्टेटमेंट और सीमाओं का पालन करें।

दूसरों से सीखें

समुदाय समाधान

अभी तक कोई प्रकाशित समाधान नहीं। पहला साझा करने के लिए इस चुनौती को हल करें।