M
M
MonsterAndrew2019-02-17 17:45:04
C++ / C#
MonsterAndrew, 2019-02-17 17:45:04

How to change the order of digits in a multi-digit number?

A multi-digit number N is given. It is necessary to remake it so that first its even digits are in the same order, and then the odd ones. The order of the numbers must be preserved. For example, 12345 -> 24135

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey delphinpro, 2019-02-17
@delphinpro

We loop through the number, dividing it by 10 on each iteration, until the number decreases to zero.
Thus, we will run through all the categories, starting with the youngest.
The digit (power of ten) will be stored separately for even and odd numbers.
We will also separately sum the even and odd digits.
At each iteration, we get the value of the digit (this is the remainder of dividing by 10)
If the digit is odd, multiply by the current degree and sum with odd numbers, otherwise the same with even numbers.
At the end of the cycle, we will have a fixed bit depth of the resulting odd number (we will have an odd number, by condition, in the lower digits of the result). Multiply an even number by 10 to that power and add it to an odd number.
Profit!
I probably don't explain very clearly. I will show the implementation in javascript:

the code
let number = 12345;
let resultEven = 0;
let resultOdd = 0;
let nEven = 0; // разрядность числа (нечетные числа)
let nOdd = 0; // разрядность числа (четные числа)

while (number > 0) {
  let digit = number % 10;
  if (digit % 2 !== 0) {
    resultEven += digit * Math.pow(10, nEven++);
  } else {
    resultOdd += digit * Math.pow(10, nOdd++);
  }
  number = Math.floor(number / 10);
}

let result = resultEven + resultOdd * Math.pow(10, nEven);

R
Rodion Kudryavtsev, 2019-02-17
@rodkud

First you select the numbers %1000, %100, %10, units. These numbers are put into an array, and you change the mirror elements of the array.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question