Questions Tagged With conversionhttps://discuss.codechef.com/tags/conversion/?type=rssquestions tagged <span class="tag">conversion</span>enMon, 21 May 2018 22:32:40 +0530java program to convert integer to Roman numbers and vice versahttps://discuss.codechef.com/questions/49846/java-program-to-convert-integer-to-roman-numbers-and-vice-versa<p>java program to convert integer to Roman numbers and vice versa</p>parthicserajMon, 18 Aug 2014 12:30:37 +0530https://discuss.codechef.com/questions/49846/java-program-to-convert-integer-to-roman-numbers-and-vice-versaconversionjavainvalid conversion of pointers using malloc functionhttps://discuss.codechef.com/questions/833/invalid-conversion-of-pointers-using-malloc-function<pre><code>#include<stdio.h>
#include<stdlib.h>
struct tree{int data;
struct tree*right,*left;
};
void insert(struct tree**,int);
void inorder(struct tree*);
int main()
{ struct tree *head=NULL;
insert(&head,5);
insert(&head,9);
insert(&head,8);
insert(&head,6);
insert(&head,2);
insert(&head,15);
inorder(head);
return 0;
}
void insert(struct tree **head,int i)
{struct tree*temp=*head;
if(temp==NULL)
{temp=malloc(sizeof(struct tree));
temp->right=NULL;
temp->left=NULL;
*head=temp;
}
else
{ if(temp->data>i)
insert(&(temp->left),i);
else
insert(&(temp->right),i);
}
}
void inorder(struct tree*head)
{if(head)
{inorder(head->left);
printf("%d",head->data);
inorder(head->right);
}
}
</code></pre>
<p>here in the above code most of the online compiler are saying invalid conversion of temp=malloc(sizeof(struct tree)); <br>
</p>
<p>cn any one help me?</p>halfbakedThu, 24 May 2012 04:22:45 +0530https://discuss.codechef.com/questions/833/invalid-conversion-of-pointers-using-malloc-functionconversioninvalidreversing array for conversion to binary numberhttps://discuss.codechef.com/questions/14956/reversing-array-for-conversion-to-binary-number<p>I'm looking to perform the decimal to binary conversion...how do I reverse the binary code stored in str[i], marked in asterisk so that I get the correct output ??</p>
<pre><code>#include <stdio.h>
#include <string.h>
void main()
{
int a, b, c, i;
int str[10];
printf("Enter an integer of your choice : ");
scanf("%d", &a);
b=a;
while (a!=0)
{
for (i=0;a>i;i++)
{
c=a%2;
str[i]=c; // ***** the binary value is stored here
printf("%d", str[i]);
a=a/2;
i++;
}
}
}
</code></pre>techbizSun, 23 Jun 2013 14:37:40 +0530https://discuss.codechef.com/questions/14956/reversing-array-for-conversion-to-binary-numberconversionreverseDecimal to binary conversion.https://discuss.codechef.com/questions/46185/decimal-to-binary-conversion<p>part of </p>
<h2>"<a href="http://www.math.grin.edu/~rebelsky/Courses/152/97F/Readings/student-binary">A TUTORIAL ON BINARY NUMBERS.</a>"</h2>
<hr>
<h2>Decimal to Binary</h2>
<p>Converting from decimal to binary notation is slightly more difficult conceptually, but can easily be done once you know how through the use of algorithms. Begin by thinking of a few examples. We can easily see that the number <code>3= 2+1</code>. and that this is equivalent to <code>(1*2^1)+(1*2^0)</code>. This translates into putting a "1" in the <code>2^1</code> column and a "1" in the <code>2^0</code> column, to get "11". Almost as intuitive is the number 5: it is obviously 4+1, which is the same as saying <code>[(2*2) +1]</code>, or <code>2^2+1</code>. This can also be written as <code>[(1*2^2)+(1*2^0)]</code>. Looking at this in columns,</p>
<pre><code> 2^2 | 2^1 | 2^0
1 0 1
</code></pre>
<p>or 101.
What we're doing here is finding the largest power of two within the number (<code>2^2=4</code> is the largest power of 2 in 5), subtracting that from the number (5-4=1), and finding the largest power of 2 in the remainder (<code>2^0=1</code> is the largest power of 2 in 1). Then we just put this into columns. This process continues until we have a remainder of 0. Let's take a look at how it works. We know that:</p>
<pre><code> 2^0=1
2^1=2
2^2=4
2^3=8
2^4=16
2^5=32
2^6=64
2^7=128
</code></pre>
<p>and so on. To convert the decimal number 75 to binary, we would find the largest power of 2 less than 75, which is 64. Thus, we would put a 1 in the 2^6 column, and subtract 64 from 75, giving us 11. The largest power of 2 in 11 is 8, or <code>2^3</code>. Put 1 in the 2^3 column, and 0 in <code>2^4</code> and <code>2^5</code>. Subtract 8 from 11 to get 3. Put 1 in the 2^1 column, 0 in <code>2^2</code>, and subtract 2 from 3. We're left with 1, which goes in <code>2^0</code>, and we subtract one to get zero. Thus, our number is <code>1001011</code>.
Making this algorithm a bit more formal gives us:</p>
<pre><code>Let D=number we wish to convert from decimal to binary
Repeat until D=0
a. Find the largest power of two in D. Let this equal P.
b. Put a 1 in binary column P.
c. Subtract P from D.
Put zeros in all columns which don't have ones.
</code></pre>
<p>This algorithm is a bit awkward. Particularly step 3, "filling in the zeros." Therefore, we should rewrite it such that we ascertain the value of each column individually, putting in 0's and 1's as we go:</p>
<pre><code>Let D= the number we wish to convert from decimal to binary
Find P, such that 2^P is the largest power of two smaller than D.
Repeat until P<0
If 2^P<=D then
put 1 into column P
subtract 2^P from D
Else
put 0 into column P
End if
Subtract 1 from P
</code></pre>
<p>Now that we have an algorithm, we can use it to convert numbers from decimal to binary relatively
painlessly. Let's try the number D=55.</p>
<pre><code>Our first step is to find P. We know that 2^4=16, 2^5=32, and 2^6=64. Therefore, P=5.
2^5<=55, so we put a 1 in the 2^5 column: 1-----.
Subtracting 55-32 leaves us with 23. Subtracting 1 from P gives us 4.
Following step 3 again, 2^4<=23, so we put a 1 in the 2^4 column: 11----.
Next, subtract 16 from 23, to get 7. Subtract 1 from P gives us 3.
2^3>7, so we put a 0 in the 2^3 column: 110---
Next, subtract 1 from P, which gives us 2.
2^2<=7, so we put a 1 in the 2^2 column: 1101--
Subtract 4 from 7 to get 3. Subtract 1 from P to get 1.
2^1<=3, so we put a 1 in the 2^1 column: 11011-
Subtract 2 from 3 to get 1. Subtract 1 from P to get 0.
2^0<=1, so we put a 1 in the 2^0 column: 110111
Subtract 1 from 1 to get 0. Subtract 1 from P to get -1.
P is now less than zero, so we stop.
</code></pre>
<hr>
<h2>Another algorithm for converting decimal to binary</h2>
<p>However, this is not the only approach possible. We can start at the right, rather than the left.</p>
<p>All binary numbers are in the form</p>
<pre><code>a[n]*2^n + a[n-1]*2^(n-1)+...+a[1]*2^1 + a[0]*2^0
</code></pre>
<p>where each <code>a[i]</code> is either a 1 or a 0 (the only possible digits for the binary system). The only way a number can be odd is if it has a 1 in the <code>2^0</code> column, because all powers of two greater than 0 are even numbers (2, 4, 8, 16...). This gives us the rightmost digit as a starting point.
Now we need to do the remaining digits. One idea is to "shift" them. It is also easy to see that multiplying and dividing by 2 shifts everything by one column: two in binary is 10, or <code>(1*2^1)</code>. Dividing <code>(1*2^1)</code> by 2 gives us <code>(1*2^0)</code>, or just a 1 in binary. Similarly, multiplying by 2 shifts in the other direction: <code>(1*2^1)*2=(1*2^2)</code> or 10 in binary. Therefore</p>
<pre><code>{a[n]*2^n + a[n-1]*2^(n-1) + ... + a[1]*2^1 + a[0]*2^0}/2
</code></pre>
<p>is equal to</p>
<pre><code>a[n]*2^(n-1) + a[n-1]*2^(n-2) + ... + a[1]2^0
</code></pre>
<p>Let's look at how this can help us convert from decimal to binary. Take the number 163. We know that since it is odd, there must be a 1 in the <code>2^0</code> column <code>(a[0]=1)</code>. We also know that it equals <code>162+1</code>. If we put the 1 in the 2^0 column, we have 162 left, and have to decide how to translate the remaining digits.</p>
<p>Two's column: Dividing 162 by 2 gives 81. The number 81 in binary would also have a 1 in the 2^0 column. Since we divided the number by two, we "took out" one power of two. Similarly, the statement <code>a[n-1]*2^(n-1) + a[n-2]*2^(n-2) + ... + a[1]*2^0</code> has a power of two removed. Our "new" <code>2^0</code> column now contains a1. We learned earlier that there is a 1 in the 2^0 column if the number is odd. Since 81 is odd, a<a href="http://www.math.grin.edu/~rebelsky/Courses/152/97F/Readings/student-binary">1</a>=1. Practically, we can simply keep a "running total", which now stands at 11 (<code>a[1]=1</code> and <code>a[0]=1</code>). Also note that a1 is essentially "remultiplied" by two just by putting it in front of a[0], so it is automatically fit into the correct column.</p>
<p>Four's column: Now we can subtract 1 from 81 to see what remainder we still must place (80). Dividing 80 by 2 gives 40. Therefore, there must be a 0 in the 4's column, (because what we are actually placing is a <code>2^0</code> column, and the number is not odd).</p>
<p>Eight's column: We can divide by two again to get 20. This is even, so we put a 0 in the 8's column. Our running total now stands at <code>a[3]=0</code>, <code>a[2]=0</code>, <code>a[1]=1</code>, and a<code>[0]=1</code>.</p>
<p>We can continue in this manner until there is no remainder to place.</p>
<pre><code> Let's formalize this algorithm:
1. Let D= the number we wish to convert from decimal to binary.
2. Repeat until D=0:
a) If D is odd, put "1" in the leftmost open column, and subtract 1 from D.
b) If D is even, put "0" in the leftmost open column.
c) Divide D by 2.
End Repeat
For the number 163, this works as follows:
1. Let D=163
2. b) D is odd, put a 1 in the 2^0 column.
Subtract 1 from D to get 162.
c) Divide D=162 by 2.
Temporary Result: 01 New D=81
D does not equal 0, so we repeat step 2.
2. b) D is odd, put a 1 in the 2^1 column.
Subtract 1 from D to get 80.
c) Divide D=80 by 2.
Temporary Result: 11 New D=40
D does not equal 0, so we repeat step 2.
2. b) D is even, put a 0 in the 2^2 column.
c) Divide D by 2.
Temporary Result:011 New D=20
2. b) D is even, put a 0 in the 2^3 column.
c) Divide D by 2.
Temporary Result: 0011 New D=10
2. b) D is even, put a 0 in the 2^4 column.
c) Divide D by 2.
Temporary Result: 00011 New D=5
2. a) D is odd, put a 1 in the 2^5 column.
Subtract 1 from D to get 4.
c) Divide D by 2.
Temporary Result: 100011 New D=2
2. b) D is even, put a 0 in the 2^6 column.
c) Divide D by 2.
Temporary Result: 0100011 New D=1
2. a) D is odd, put a 1 in the 27 column.
Subtract 1 from D to get D=0.
c) Divide D by 2.
Temporary Result: 10100011 New D=0
</code></pre>
<p>D=0, so we are done, and the decimal number 163 is equivalent to the binary number 10100011.
Since we already knew how to convert from binary to decimal, we can easily verify our result. </p>
<p><code>10100011=(1*2^0)+(1*2^1)+(1*2^5)+(1*2^7)=1+2+32+128= 163</code>.</p>
<p>ref: <a href="http://www.math.grin.edu/~rebelsky/Courses/152/97F/Readings/student-binary">http://www.math.grin.edu/~rebelsky/Courses/152/97F/Readings/student-binary</a></p>
<p>wanna practice what you learnt? try: TCHS SRM 27 250 pt: <a href="http://community.topcoder.com/stat?c=problem_statement&pm=7331&rd=10651">Brick Mystery</a></p>garakchyMon, 30 Jun 2014 09:38:06 +0530https://discuss.codechef.com/questions/46185/decimal-to-binary-conversionbinarydecimalnumbertutorialconversionConverting adjacency matrix to adjacency listshttps://discuss.codechef.com/questions/40709/converting-adjacency-matrix-to-adjacency-lists<p>Hi guys,</p>
<p>I'm now experimenting with Ford-Fulkerson Algorithm, which I am using to print the min-cut (as in, edges which comprise the min-cut).</p>
<p>However, I am having some issues with memory and I wanted to translate this code to use only adjacency lists representation, instead of adjacency matrix...</p>
<p>If someone could help me I'd be really glad, as I've spent over 72 hours with this problem... :/</p>
<pre><code>// C++ program for finding minimum cut using Ford-Fulkerson
#include <iostream>
#include <limits.h>
#include <string.h>
#include <queue>
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <cmath>
#include <functional>
using namespace std;
#define DEBUG 0
typedef pair<int,int> PII;
/* Returns true if there is a path from source 's' to sink 't' in
residual graph. Also fills parent[] to store the path */
int bfs(vector<vector<int> > rGraph, int s, int t, int parent[])
{
// Create a visited array and mark all vertices as not visited
bool visited[rGraph.size()];
memset(visited, 0, sizeof(visited));
// Create a queue, enqueue source vertex and mark source vertex
// as visited
queue <int> q;
q.push(s);
visited[s] = true;
parent[s] = -1;
// Standard BFS Loop
while (!q.empty())
{
int u = q.front();
q.pop();
for (int v=0; v< (int) rGraph.size(); v++)
{
if (visited[v]==false && rGraph[u][v] > 0)
{
q.push(v);
parent[v] = u;
visited[v] = true;
}
}
}
// If we reached sink in BFS starting from source, then return
// true, else false
return (visited[t] == true);
}
// A DFS based function to find all reachable vertices from s. The function
// marks visited[i] as true if i is reachable from s. The initial values in
// visited[] must be false. We can also use BFS to find reachable vertices
void dfs(vector<vector<int> > rGraph, int s, bool visited[])
{
visited[s] = true;
for (int i = 0; i < (int) rGraph.size(); i++)
if (rGraph[s][i] && !visited[i])
dfs(rGraph, i, visited);
}
// Prints the minimum s-t cut
vector<PII> minCut(vector<vector<int> > graph, int s, int t)
{
int u, v;
vector<PII> ans;
// Create a residual graph and fill the residual graph with
// given capacities in the original graph as residual capacities
// in residual graph
vector<vector<int> > rGraph; // rGraph[i][j] indicates residual capacity of edge i-j
//<----------------------------------------------------------------------------------------------------------
rGraph.resize(graph.size());
for(int i = 0; i < (int) graph.size(); i++)
{
rGraph[i].resize(graph.size());
}
//-------------------------------------------------------------------------------------------------------->
for (u = 0; u < (int) graph.size(); u++)
for (v = 0; v < (int) graph.size(); v++)
rGraph[u][v] = graph[u][v];
int parent[rGraph.size()]; // This array is filled by BFS and to store path
// Augment the flow while tere is path from source to sink
while (bfs(rGraph, s, t, parent))
{
// Find minimum residual capacity of the edhes along the
// path filled by BFS. Or we can say find the maximum flow
// through the path found.
int path_flow = INT_MAX;
for (v=t; v!=s; v=parent[v])
{
u = parent[v];
path_flow = min(path_flow, rGraph[u][v]);
}
// update residual capacities of the edges and reverse edges
// along the path
for (v=t; v != s; v=parent[v])
{
u = parent[v];
rGraph[u][v] -= path_flow;
rGraph[v][u] += path_flow;
}
}
// Flow is maximum now, find vertices reachable from s
bool visited[rGraph.size()];
memset(visited, false, sizeof(visited));
dfs(rGraph, s, visited);
// Print all edges that are from a reachable vertex to
// non-reachable vertex in the original graph
for (int i = 0; i < (int) rGraph.size(); i++)
for (int j = 0; j < (int) rGraph.size(); j++)
if (visited[i] && !visited[j] && graph[i][j])
{
//cout << i << " - " << j << endl;
ans.push_back(make_pair(i,j));
}
return ans;
}
// Driver program to test above functions
int main()
{
// Let us create a graph shown in the above example
/* int graph[V][V] = { {0, 16, 13, 0, 0, 0},
{0, 0, 10, 12, 0, 0},
{0, 4, 0, 0, 14, 0},
{0, 0, 9, 0, 0, 20},
{0, 0, 0, 7, 0, 4},
{0, 0, 0, 0, 0, 0}
};*/
int n,m;
cin >> n >> m;
vector<vector<int> > G;
G.resize(n);
for(int i = 0; i < n; i++)
{
G[i].resize(n);
}
//for(int i = 0; i < n; i++)
//{
//for(int j = 0; j < n; j++)
//{
//cin >> G[i][j];
//}
//}
//reads edge
for(int i = 0; i < m; i++)
{
int u,v;
cin >> u >> v;
G[u][v] = 1; //all vertexes are assumed to have weight 1
G[v][u] = 1;
}
int h;
cin >> h;
for(int i = 0; i < h; i++)
{
int npcs;
cin >> npcs;
vector<int> vv(npcs);
vector<PII> p;
for(int i = 0; i < npcs; i++)
{
//int pc;
cin >> vv[i];
}
int answer = INT_MAX;
for(int i = 1; i < (int) vv.size(); i++)
{
p = minCut(G,vv[0],vv[i]);
answer = min(answer,(int) p.size());
}
cout << answer << endl;
}
//prints filled matrix for debug purposes... TODO: Add debug flag
if(DEBUG){
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
cout << G[i][j] << " ";
}
cout << endl;
}
}
//minCut(G, 1, 0);
//cout << p.size() << endl;
return 0;
}
</code></pre>
<p>Note: my main issue seems to be how can I use C++ iterators to "pass" the adjacency list to both DFS and BFS in order not to get lots of segfaults... As I've rarely used adjacency lists and as my iterator knowledge is poor, I'd like some guidance :D
Best,</p>
<p>Bruno</p>kurumaMon, 31 Mar 2014 23:11:49 +0530https://discuss.codechef.com/questions/40709/converting-adjacency-matrix-to-adjacency-listsconversionadjacencyhelplistshow to find the binary equivalent of a negative decimal number. for instance what is the binary equivalent of -2?https://discuss.codechef.com/questions/16636/how-to-find-the-binary-equivalent-of-a-negative-decimal-number-for-instance-what-is-the-binary-equivalent-of-2<p>pls explain the procedure </p>imcodeFri, 05 Jul 2013 21:47:40 +0530https://discuss.codechef.com/questions/16636/how-to-find-the-binary-equivalent-of-a-negative-decimal-number-for-instance-what-is-the-binary-equivalent-of-2binarydecimalbaseconversionjsp(conversion of string to date)https://discuss.codechef.com/questions/64306/jspconversion-of-string-to-date<p>html command <input type="date" name="dat"/>. here date is a string. how do i convert it in datatype "date" using JSP?</p>avisarafThu, 12 Feb 2015 11:02:20 +0530https://discuss.codechef.com/questions/64306/jspconversion-of-string-to-datedateconversionjspstringConversion from integer/floating-point to stringhttps://discuss.codechef.com/questions/65686/conversion-from-integerfloating-point-to-string<p>Please tell me how can I convert integers such as 5,7,89,etc. or floating-ppoints like 5.90,7.45,etc. to strings like "5","5.90",etc.</p>anupam_dattaSat, 07 Mar 2015 19:32:16 +0530https://discuss.codechef.com/questions/65686/conversion-from-integerfloating-point-to-stringconversionWriting own parse functions in Java.https://discuss.codechef.com/questions/83802/writing-own-parse-functions-in-java<p>Hello Everyone,
I have seen many programmers write their own functions to convert String into integer, float or double, when they code in Java. I want to ask just one thing that is it faster than using built in functions provided by Java? Please bear with the question if you find it very childish or basic.</p>nitin2n33Tue, 02 Aug 2016 10:55:25 +0530https://discuss.codechef.com/questions/83802/writing-own-parse-functions-in-javaconversionjavastringdoublefloatparsersintegerprogrammerKOL15A - Editorialhttps://discuss.codechef.com/questions/77475/kol15a-editorial<h1>PROBLEM LINK:</h1>
<p><a href="http://www.codechef.com/ACMKOL15/problems/KOL15A">Contest</a><br>
<a href="http://www.codechef.com/problems/KOL15A">Practice</a></p>
<p><strong>Author:</strong> <a href="https://www.codechef.com/users/pnkjjindal">Pankaj Jindal</a><br>
<strong>Tester:</strong> <a href="http://www.codechef.com/users/kevinsogo">Kevin Atienza</a><br>
<strong>Editorialist:</strong> <a href="http://www.codechef.com/users/kevinsogo">Kevin Atienza</a></p>
<h1>DIFFICULTY:</h1>
<p>Simple</p>
<h1>PREREQUISITES:</h1>
<p>Type conversion, strings</p>
<h1>PROBLEM:</h1>
<p>Given a string of alphanumeric characters, print the sum of the digits.</p>
<h1>EXPLANATION:</h1>
<p>This is the easiest problem in the contest. Straightforward solutions will likely pass.</p>
<p>The idea is to iterate through the input string, filter out the non-digits, convert the digit characters into actual integers, and sum them. The following are a few sample implementations.</p>
<p>C:</p>
<pre><code>#include <stdio.h>
char s[1111];
int main() {
int cases, cas, i, total;
scanf("%d", &cases);
for (cas = 0; cas < cases; cas++) {
scanf("%s", s);
total = 0;
for (i = 0; s[i]; i++) {
if ('0' <= s[i] && s[i] <= '9') total += s[i] - '0';
}
printf("%d\n", total);
}
return 0;
}
</code></pre>
<p>C++:</p>
<pre><code>#include <iostream>
using namespace std;
int main() {
int cases;
cin >> cases;
for (int cas = 0; cas < cases; cas++) {
string s;
cin >> s;
int total = 0;
for (int i = 0; s[i]; i++) {
if ('0' <= s[i] && s[i] <= '9') total += s[i] - '0';
}
cout << total << endl;
}
return 0;
}
</code></pre>
<p>Java:</p>
<pre><code>import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(<a href="http://System.in">System.in</a>);
int cases = sc.nextInt();
for (int cas = 0; cas < cases; cas++) {
String s = sc.next();
int total = 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if ('0' <= ch && ch <= '9') {
total += ch - '0';
}
}
System.out.println(total);
}
}
}
</code></pre>
<h1>Implementation details</h1>
<p><strong>How to check if a character is a digit</strong></p>
<p>All the above codes use the snippet <code>'0' <= ch && ch <= '9'</code> to determine if a character <code>ch</code> is a digit. This works because the <code>char</code> type in C, C++ and Java are implemented as a single byte representing the ASCII code of the character, and the digit characters <code>'0'</code> to <code>'9'</code> are consecutive ASCII codes. In fact, you can use a similar technique to check if <code>ch</code> is a lowercase character: <code>'a' <= ch && ch <= 'z'</code>. </p>
<p><strong>How to convert a character to an integer (if it is a digit)</strong></p>
<p>Since characters are represented simply as bytes, we can perform arithmetic with them. This gives us a way to convert a digit character to a number. To convert a digit character <code>ch</code> to a number from $0$ to $9$, we simply use <code>ch - '0'</code>.</p>
<p>Note that a character being represented as a byte is not universal. In some other languages such as Python or Ruby, characters are actually represented as strings of length one, and although comparison between chars still work, you can't necessarily perform arithmetic between chars. For example, in Python, <code>'l' - 'a'</code> would be an error. But usually there are still ways to get the ASCII value of a character. For example, in Python, you would use the <code>ord</code> and <code>chr</code> functions to convert to and from an integer, respectively. </p>
<h1>Common errors</h1>
<p>This is the easiest problem in the contest. However, that doesn't mean nothing can go wrong with your submission. Lots of things can go wrong, from major problems down to simple gaffes such as choosing the wrong language while submitting! You must be prepared to handle these mistakes, because debugging is part of a programmer's life, and in fact usually takes more time than actual coding.</p>
<p>One common error is forgetting to initialize variables, as in the following:</p>
<pre><code>#include <stdio.h>
char s[1111];
int main() {
int cases, cas, i, total = 0;
scanf("%d", &cases);
for (cas = 0; cas < cases; cas++) {
scanf("%s", s);
for (i = 0; s[i]; i++) {
if ('0' <= s[i] && s[i] <= '9') total += s[i] - '0';
}
printf("%d\n", total);
}
return 0;
}
</code></pre>
<p>This one could be quite misleading because the line <code>total = 0</code> initializing the <code>total</code> variable is present. It's just that it's outside the loop, so it doesn't reset to <code>0</code> for the following test case! Consequently, your program will most likely get wrong answers for all but the first test case. </p>
<p>One way to detect this is possibly to add an identical test case in your sample input. If the answers you got are different, then most likely something's wrong. Also, to be sure, declare variables only on scopes they're needed, as shown in the C++ and Java examples above.</p>
<p>Another error is allocating an array too small for the input string. Remember that when given constraints such as $|S| \le 1000$, judges will most likely test out extremes, so allocating an array of size 200 will not be enough. In fact, for C or C++ an array of size $1000$ might not be enough too, because strings in those languages are terminated with a null character <code>\0</code>. You need at least $1001$ for the null character to be accommodated. (In fact, the examples above use $1111$ just to be extra cautious.) </p>
<h1>Readability</h1>
<p>Another way to help you debug your code is to ensure your code is readable and clear. This includes formatting your code properly and possibly adding a few comments. In general, try to put yourself in your teammate's shoe and see if he/she will understand the code just by reading it, without you explaining it.</p>
<p>Here are some things about readability related to this problem:</p>
<ul>
<li>When hardcoding the digits, don't write the ASCII values. Instead, use the actual character <code>'0'</code>, <code>'a'</code>, etc. Technically, <code>'0'</code> would work the same in most cases as <code>48</code> (<code>'0'</code>'s ASCII code), but <code>'0'</code> is much clearer than a random <code>48</code> found in code.</li>
<li>Simplicity is important. There's no need for very advanced programming patterns for something as simple as this. If you check the examples above, you find that they're simple and straight to the point, and it also has the desirable consequence of being clear and readable.</li>
<li>Some submissions convert chars to ints by first converting the char to a string and then parsing it into an int. Please don't do that. It's harder to read than the methods above, and is actually much more inefficient.</li>
<li>If possible, try to use library functions that will help you with the task if you know them. In actual real life coding work, it always pays to check whether a particular task already has a builtin function for it or has already been implemented in a library. In our case, you could use <code>Character.isDigit</code> in Java or <code>isdigit</code> in C++ to check whether a char is a digit.</li>
</ul>
<h1>Miscellanea</h1>
<p>Here we mention other common errors and things to remember.</p>
<ul>
<li>Don't forget to print a newline at the end of each test case! To be sure, try it yourself first with a couple of test cases and see if they output as expected. Command line tools such as <code>diff</code> or <code>fc</code> are helpful for this task and guards against manual checking which is unreliable.</li>
<li>Use zero-indexing. It's idiomatic in many languages including C, C++ and Java. Even though some problems use one-indexing, it's usually helpful to convert to zero indexing in most languages, especially if you're gonna use some builtin functions that assume zero indexing.</li>
<li>Don't print unnecessary stuff like "Please enter the number of test cases: ". These are considered part of your output and so your solution will be marked wrong. The goal is to <em>exactly match</em> the contents of the judge's output file. </li>
</ul>
<p><strong>Language-specific things</strong></p>
<ul>
<li>When using <code>scanf</code> to take a string, use <code>scanf("%s",s);</code> instead of the incorrect <code>scanf("%s",&s);</code>. </li>
<li>When copy-pasting Java code to be submitted to CodeChef, use <code>Main</code> as your public class name (as stated in <a href="https://www.codechef.com/wiki/sample-solutions">https://www.codechef.com/wiki/sample-solutions</a> ). It's because Java requires the file name and public class name to be the same, but since you copy-pasted code, CodeChef doesn't know the public class name and could have a harder time figuring it out from code. It's easier to just assume it's something, say, <code>Main</code>.</li>
</ul>
<p><strong>Contest-specific stuff</strong></p>
<p>These are things usually good to be done during contests but are worth keeping in mind that they are considered bad practice in industry code.</p>
<ul>
<li>In Java, there are times when some methods have checked exceptions, such as <code>IOException</code> for <code>BufferedReader.readLine()</code>, requiring you to handle them with bulky <code>try</code>-<code>catch</code> blocks. In these cases, you can just declare <code>throws Exception</code> in your main method. This is very much not recommended in production code, but in a contest, it's very convenient.</li>
<li>In Java, instead of importing each class separately, you can import everything from a single package using "import *", e.g. <code>import java.util.*;</code>. Of course this is not recommended at work because it makes it harder to keep track of where each used class is defined, but during contests you don't really need to worry about it.</li>
<li>Instead of having to type <code>std::cin</code> all the time, you can add <code>using namespace std</code> in your C++ code so you can just use <code>cin</code>. It's also considered <a href="http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice">bad practice</a> in real life. Nonetheless, it's also convenient, makes code a bit clearer, and can cut down typing time. Even then, people using it must be wary, because problems such as <a href="http://stackoverflow.com/questions/2712076/how-to-use-an-iterator/2712125#2712125">this</a> and <a href="http://stackoverflow.com/questions/13402789/confusion-about-pointers-and-references-in-c">this</a> might occur.</li>
</ul>
<h1>Time Complexity:</h1>
<p>$O(N)$ </p>
<h1>AUTHOR'S AND TESTER'S SOLUTIONS:</h1>
<p><a href="https://www.codechef.com/download/Solutions/ACMKOL15/Setter/KOL15A.cpp">setter</a><br>
<a href="https://www.codechef.com/download/Solutions/ACMKOL15/Setter/KOL15A.cpp">tester</a> </p>kevinsogoTue, 01 Dec 2015 21:52:24 +0530https://discuss.codechef.com/questions/77475/kol15a-editorialsimpleconversionstringseditorialacmkol15hexa decimal number addition in javahttps://discuss.codechef.com/questions/127271/hexa-decimal-number-addition-in-java<p>input 2 hexadecimal numbers and then add them and print the result without any conversion to decimal .we have to code as we simply add them in reality</p>yashikamMon, 21 May 2018 22:32:40 +0530https://discuss.codechef.com/questions/127271/hexa-decimal-number-addition-in-javaconversionConversionhttps://discuss.codechef.com/questions/68056/conversion<p>Shree was in USA. She has just returned from USA and planned for a pani puri treat with his colleagues Zakky, Davi Prasad, Deepak, Suman and Vidyaranya. Davi Prasd ate "N" pani puris that is equivalent to pani puris eaten by suman and zakky, Now Deepak started competing with Davi Prasad and ate pani puris which is same as pani puri eaten by Zakky and Davi Prasad. Mean time Vidyaranya was checking his e-mail but seeing Deepak he became furious and ate pani puri i.e equals to Davi Prasad & Suman. Since Shree is very conscious about her health she only ate 5 pani puris. As she is used to with $USD after eating pani puri she asked the vendor for the bill in $USD. A pani puri costs 50 paisa. Vendor has no idea about $USD, help him to calculate the bill in $USD.
The user pass no of pani puri and current amunt of dollar
The Program should be in java language</p>
<p>Please provide me the source code of this question as soon as possible</p>coolpoooSat, 18 Apr 2015 14:06:34 +0530https://discuss.codechef.com/questions/68056/conversiondollarconversionjavain