简体   繁体   中英

Determine if all digits of the sum of n and swapped n are odd

I need to determine if all the digits of the sum of n numbers and swapped n are odd.

For example:

36 + 63 = 99 (9 and 9 are both odd)

409 + 904 = 1313 (1 and 3 are both odd)

Visual Studio builds my code and it runs, but it doesn't return an answer.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            long num = Convert.ToInt64(Console.Read());
            long vol = voltea(num);
            long sum = num + vol;

            bool simp = simpares(sum);

            if (simp == true)
                Console.Write("Si");
            else
                Console.Write("No");

        }

        static private bool simpares(long x)
        {
            bool s = false;
            long [] arreglo  = new long [1000];
            while ( x > 0)
            {
                arreglo [x % 10] ++;
                x /=10;
            }

            for (long i=0 ; i <= arreglo.Length ; i++)
            {
                if (arreglo [i]%2 != 0)
                    s = true;
            }
            return s;
        }

        static private long voltea(long x)
        {
            long v = 0;

            while (v > 0) 
            {
                v = 10 * v + x % 10;
                x /= 10;
            }
            return v;
        }
    }
}

I'm not sure what's wrong with your code, but I was thinking an easier way to accomplish this would be to use strings, rather than doing all the divisions and mods by 10.

  1. Convert original number to string, reverse the string, then convert that back to a long
  2. Add the original and reversed numbers
  3. Convert the sum to a string
  4. Loop over the result string and check to see if each digit is odd

It's not too clear what you mean by "Doesn't return an answer".

Add:

        Console.ReadKey();
        Console.ReadLine();

At the end of your Main function. I'd hazard a guess that you're not seeing an answer because the console is closing on you.

EDIT:

Found it:

for (long i=0 ; i <= arreglo.Length ; i++)

Index out of bounds. That should be:

for (long i=0 ; i < arreglo.Length ; i++)

i should be "Less than" arreglo, not "Less than or equal to"

EDIT2:

This is why your current code is broken. I'd highly recommend also looking at alternative methods of solving the problem. See Andy White's Answer.

It looks to me like you might have an infinite loop and a loop that never enters.

// because v = 0, the while will never execute
long v = 0;

while (v > 0) 
{
    v = 10 * v + x % 10;
    x /= 10;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM