Comprobar si los dígitos de un número aumentan y disminuyen alternativamente

Dado un número N , la tarea es verificar si los dígitos del número son crecientes y decrecientes alternativamente. Si el número de dígitos es inferior a 3 , devuelve falso . Por ejemplo, si d1, d2 y d3 son los dígitos de N, d1 < d2 > d3 debe cumplirse .
Ejemplos :

Entrada : N = 6834
Salida : verdadero
Explicación : Los dígitos de N aumentan y disminuyen alternativamente, es decir, 6 < 8 > 3 < 4
Entrada : N = 32
Salida : falso

 

Enfoque : la tarea se puede resolver convirtiendo el entero dado en una string. Itere sobre la string y verifique si los caracteres adyacentes siguen las condiciones dadas o no.
A continuación se muestra la implementación del enfoque anterior:

C++

// C++ implementation for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Utility function to check if
// the digits of the current
// integer forms a wave pattern
bool check(int N)
{
    // Convert the number to a string
    string S = to_string(N);
 
    // Loop to iterate over digits
    for (int i = 0; i < S.size(); i++) {
        if (i == 0) {
 
            // Next character of
            // the number
            int next = i + 1;
 
            // Current character is
            // not a local minimum
            if (next < S.size()) {
                if (S[i] >= S[next]) {
 
                    return false;
                }
            }
        }
 
        else if (i == S.size() - 1) {
 
            // Previous character of
            // the number
            int prev = i - 1;
            if (prev >= 0) {
 
                // Character is a
                // local maximum
                if (i & 1) {
 
                    // Character is not
                    // a local maximum
                    if (S[i] <= S[prev]) {
                        return false;
                    }
                }
                else {
                    // Character is a
                    // local minimum
                    if (S[i] >= S[prev]) {
                        return false;
                    }
                }
            }
        }
        else {
            int prev = i - 1;
            int next = i + 1;
            if (i & 1) {
 
                // Character is a
                // local maximum
                if ((S[i] > S[prev])
                    && (S[i] > S[next])) {
                }
                else {
                    return false;
                }
            }
            else {
                // Character is a
                // local minimum
                if ((S[i] < S[prev])
                    && (S[i] < S[next])) {
                }
                else {
                    return false;
                }
            }
        }
    }
    return true;
}
 
// Driver Code
int main()
{
    int N = 64;
    cout << (check(N) ? "true" : "false");
}

Java

// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG {
 
  // Utility function to check if
  // the digits of the current
  // integer forms a wave pattern
  static Boolean check(int N)
  {
     
    // Convert the number to a string
    String S = Integer.toString(N);
 
    // Loop to iterate over digits
    for (int i = 0; i < S.length(); i++) {
      if (i == 0) {
 
        // Next character of
        // the number
        int next = i + 1;
 
        // Current character is
        // not a local minimum
        if (next < S.length()) {
          if (S.charAt(i) >= S.charAt(next)) {
 
            return false;
          }
        }
      }
 
      else if (i == S.length() - 1) {
 
        // Previous character of
        // the number
        int prev = i - 1;
        if (prev >= 0) {
 
          // Character is a
          // local maximum
          if (i % 2 == 1) {
 
            // Character is not
            // a local maximum
            if (S.charAt(i) <= S.charAt(prev)) {
              return false;
            }
          }
          else {
            // Character is a
            // local minimum
            if (S.charAt(i) >= S.charAt(prev)) {
              return false;
            }
          }
        }
      }
      else {
        int prev = i - 1;
        int next = i + 1;
        if (i % 2 == 1) {
 
          // Character is a
          // local maximum
          if ((S.charAt(i) > S.charAt(prev))
              && (S.charAt(i) > S.charAt(next))) {
          }
          else {
            return false;
          }
        }
        else
        {
           
          // Character is a
          // local minimum
          if ((S.charAt(i) < S.charAt(prev))
              && (S.charAt(i) < S.charAt(next))) {
          }
          else {
            return false;
          }
        }
      }
    }
    return true;
  }
 
  // Driver Code
  public static void main (String[] args) {
    int N = 64;
    if(check(N) == true)
      System.out.print("true");
    else
      System.out.print("false");
  }
}
 
// This code is contributed by hrithikgarg03188

Python3

# Python implementation for the above approach
 
# Utility function to check if
# the digits of the current
# integer forms a wave pattern
def check(N):
    # Convert the number to a string
    S = str(N)
 
    # Loop to iterate over digits
    for i in range(len(S)):
        if (i == 0):
 
            # Next character of
            # the number
            next = i + 1
 
            # Current character is
            # not a local minimum
            if (next < len(S)):
                if (S[i] >= S[next]):
                    return False
 
        elif (i == len(S) - 1):
 
            # Previous character of
            # the number
            prev = i - 1
            if (prev >= 0):
 
                # Character is a
                # local maximum
                if (i & 1):
 
                    # Character is not
                    # a local maximum
                    if (S[i] <= S[prev]):
                        return False
                else:
                    # Character is a
                    # local minimum
                    if (S[i] >= S[prev]):
                        return False
        else:
            prev = i - 1
            next = i + 1
            if (i & 1):
 
                # Character is a
                # local maximum
                if ((S[i] > S[prev]) and (S[i] > S[next])):
                    print("", end="")
                else:
                    return False
            else:
                # Character is a
                # local minimum
                if ((S[i] < S[prev]) and (S[i] < S[next])):
                    print("", end="")
                else:
                    return False
    return True
 
 
# Driver Code
 
N = 64
print("true" if check(N) else "false")
 
# This code is contributed by Saurabh Jaiswal

C#

// C# program for the above approach
using System;
 
class GFG {
 
  // Utility function to check if
  // the digits of the current
  // integer forms a wave pattern
  static bool check(int N)
  {
 
    // Convert the number to a string
    string S = N.ToString();
 
    // Loop to iterate over digits
    for (int i = 0; i < S.Length; i++) {
      if (i == 0) {
 
        // Next character of
        // the number
        int next = i + 1;
 
        // Current character is
        // not a local minimum
        if (next < S.Length) {
          if (S[i] >= S[next]) {
 
            return false;
          }
        }
      }
 
      else if (i == S.Length - 1) {
 
        // Previous character of
        // the number
        int prev = i - 1;
        if (prev >= 0) {
 
          // Character is a
          // local maximum
          if (i % 2 == 1) {
 
            // Character is not
            // a local maximum
            if (S[i] <= S[prev]) {
              return false;
            }
          }
          else {
            // Character is a
            // local minimum
            if (S[i] >= S[prev]) {
              return false;
            }
          }
        }
      }
      else {
        int prev = i - 1;
        int next = i + 1;
        if (i % 2 == 1) {
 
          // Character is a
          // local maximum
          if ((S[i] > S[prev])
              && (S[i] > S[next])) {
          }
          else {
            return false;
          }
        }
        else
        {
 
          // Character is a
          // local minimum
          if ((S[i] < S[prev])
              && (S[i] < S[next])) {
          }
          else {
            return false;
          }
        }
      }
    }
    return true;
  }
 
  // Driver Code
  public static void Main () {
    int N = 64;
    if(check(N) == true)
      Console.Write("true");
    else
      Console.Write("false");
  }
}
 
// This code is contributed by Samim Hossain Mondal.

Javascript

<script>
// Javascript implementation for the above approach
 
// Utility function to check if
// the digits of the current
// integer forms a wave pattern
function check(N){
    // Convert the number to a string
    let S = new String(N);
 
    // Loop to iterate over digits
    for (let i = 0; i < S.length; i++) {
        if (i == 0) {
 
            // Next character of
            // the number
            let next = i + 1;
 
            // Current character is
            // not a local minimum
            if (next < S.length) {
                if (S[i] >= S[next]) {
                    return false;
                }
            }
        }
 
        else if (i == S.length - 1) {
 
            // Previous character of
            // the number
            let prev = i - 1;
            if (prev >= 0) {
 
                // Character is a
                // local maximum
                if (i & 1) {
 
                    // Character is not
                    // a local maximum
                    if (S[i] <= S[prev]) {
                        return false;
                    }
                }
                else {
                    // Character is a
                    // local minimum
                    if (S[i] >= S[prev]) {
                        return false;
                    }
                }
            }
        }
        else {
            let prev = i - 1;
            let next = i + 1;
            if (i & 1) {
 
                // Character is a
                // local maximum
                if ((S[i] > S[prev])
                    && (S[i] > S[next])) {
                }
                else {
                    return false;
                }
            }
            else {
                // Character is a
                // local minimum
                if ((S[i] < S[prev])
                    && (S[i] < S[next])) {
                }
                else {
                    return false;
                }
            }
        }
    }
    return true;
}
 
// Driver Code
 
let N = 64;
document.write(check(N) ? "true" : "false");
 
// This code is contributed by gfgking.
</script>
Producción

false

Complejidad de tiempo : O(N), N es el número de dígitos
Espacio auxiliar : O(N)

Publicación traducida automáticamente

Artículo escrito por Code_r y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *